Counting even and odd numbers in an array involves iterating through each element and checking whether it is divisible by 2. Even numbers have a remainder of 0 when divided by 2, while odd numbers do not.
Java Program to Count Even and Odd Numbers in an Array
This Java program counts the number of even and odd numbers in an array by iterating through its elements and using the modulus operator (%
) to check divisibility by 2.
package com.javacodepoint.array;
public class CountEvenOdd {
public static void main(String[] args) {
int[] arr = {10, 15, 20, 25, 30, 35, 40};
int evenCount = 0;
int oddCount = 0;
// Count even and odd numbers
for (int num : arr) {
if (num % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}
System.out.println("Number of even numbers: " + evenCount);
System.out.println("Number of odd numbers: " + oddCount);
}
}
OUTPUT:
Number of even numbers: 4
Number of odd numbers: 3
Read Also: Find Average of Odd and Even Numbers in Array Java.