Java how to find odd and even in a array

Java how to find odd and even in a array

To find the odd and even numbers in an array in Java, you can use a loop to iterate over the array and use the modulo operator (%) to check if each number is odd or even.

Here's an example of how to find the odd and even numbers in an array in Java:

re‮ref‬ to:lautturi.com
int[] numbers = {1, 2, 3, 4, 5};

for (int number : numbers) {
  if (number % 2 == 0) {
    System.out.println(number + " is even");
  } else {
    System.out.println(number + " is odd");
  }
}

In the above example, a for-each loop is used to iterate over the array and check if each number is even or odd. If the number is even, a message is printed to the console stating that the number is even. If the number is odd, a message is printed stating that the number is odd.

To check if a number is even, the modulo operator is used to determine if the number is divisible by 2. If the number is divisible by 2, the result of the modulo operation will be 0, which means the number is even. If the number is not divisible by 2, the result of the modulo operation will be 1, which means the number is odd.

Keep in mind that this example only works for arrays of integers. If you are working with an array of a different data type, you may need to use a different approach to find the odd and even numbers. For example, you could use the instanceof operator to check if the elements of the array are instances of the Integer class and then use the modulo operator to determine if they are odd or even.

Created Time:2017-11-03 23:27:08  Author:lautturi