1

Are there any other ways to print the position of your element inside the array? Even[position in the array]=even numbers Odd[position in the array]=odd numbers

public class samt {
    public static void main(String[] args){
        int Num[] = {1,2,3,4,5,6,7,8,9,10};
        int ctr=1, ctr2=0;
        for(int i=0;i<10;i++) {
            if(Num[i]%2==0) {       
                System.out.print("Even"+"["+ctr+"]=");
                System.out.println(Num[i]);
                ctr+=2;
            }
        }
        for(int i=0;i<10;i++) {
            if(Num[i]%2!=0) {
                System.out.print("Odd"+"["+ctr2+"]=");
                System.out.println(Num[i]);
                ctr2+=2;
            }   
        }   
    }   
}
6
  • 1
    Yes, there are other ways. Are you looking for anything specific? In other words: Why are you looking for an alternative? Does it have to be more performant, more consice or something else? Commented Jul 8, 2022 at 8:45
  • just want to make it shorter. all my codes are long I'm trying things to shorten and apply those to my other codes. any will do Commented Jul 8, 2022 at 8:57
  • Hey you can just place a else clause in your first for loop. In this clause you can place the odd output. You only have even or odd numbers. The second for loop is no longer needed. This will half your runtime, what is not relevant on array with 10 entries but still. Commented Jul 8, 2022 at 9:09
  • 2
    @时间只会一直走 fair point. I do not look at this aspect of the code. If it is acceptable to get the output at the end of the algorithm you can use two StringBuilder and print the result at the end. Commented Jul 8, 2022 at 9:21
  • 1
    @Tr1monster nice try! i am still thinking about how to move the cursor up a line! Commented Jul 8, 2022 at 9:26

1 Answer 1

1

If your only goal is to shorten your code you can use lists and filter for even and odd numbers:

Integer[] num = {1,2,3,4,5,6,7,8,9,10};
List<Integer> list = Arrays.asList(num);
List<Integer> even = list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());
List<Integer> odd = list.stream().filter(n -> n % 2 == 1).collect(Collectors.toList());
even.forEach(n -> System.out.println("Even" + "["+ list.indexOf(n) + "]=" + n));
odd.forEach(n -> System.out.println("Odd" + "["+ list.indexOf(n) + "]=" + n));

With this the output lookes the same as with your code:

Even[1]=2
Even[3]=4
Even[5]=6
Even[7]=8
Even[9]=10
Odd[0]=1
Odd[2]=3
Odd[4]=5
Odd[6]=7
Odd[8]=9

Note that the runtime of this is probably longer than with your attempt.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.