Home > front end >  How do I display only even numbers in an array while using for loop?
How do I display only even numbers in an array while using for loop?

Time:04-17

I'm trying to display only even numbers(0-18) in an array while using for-loop.

int[] numbers = new int[38];
    for(int i=0; i < numbers.length;   i)
    numbers[i] = i / 2;
    for(int i=0; i < numbers.length; i  )
    System.out.print(numbers[  i]   " ");
    System.out.println();

So far I have 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 displaying

I tried changing numbers[i] = i / 2; to numbers[i] = i % 2; but I would just get 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

CodePudding user response:

public class DisplayEvenNumbers {
    public static void main(String args[]) {
      int[] numbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
      for (int number : numbers) {
          if (number % 2 == 0) {
              System.out.println(number);
          }
      }
    }
}

All you need is to have an array with the range of numbers within which you want to display even numbers, iterate through the array checking if the value in each position is even, and if it is, display it.

Actually you don't even need the array, you can just use a loop and operate in a similar fashion with the index of the loop:

public class DisplayEvenNumbers2 {
    public static void main(String args[]) {
      int[] numbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
      for (int i = 1; i < 19; i  ) {
          if (i % 2 == 0) {
              System.out.println(i);
          }
      }
    }
}

Both examples are functionally equivalent and display the even numbers 2, 4, 6, 8, 10, 12, 14, 16 and 18, each on its own line.

  • Related