Learn how to count even and odd numbers in an array using Java. This program traverses each array element, checks whether it is even or odd using the modulus operator , maintains separate counters, and displays the total count of even and odd numbers.
Code Explanation (Step-by-Step)
- Creates a Scanner object to read input from the keyboard.
- Creates an integer array named a to store up to 5 elements.
- Uses the sc.nextInt() method to read the number of elements from the user and stores the value in the variable n.
- Traverses a loop to read and process each array element.
- if (a[i] % 2 == 0) checks whether the current element is divisible by 2. If it is divisible by 2, the number is even; otherwise, it is odd.
- evenNumber++ is used to increment the even number counter by 1.
- oddNumber++ is used to increment the odd number counter by 1.
- Displays the total count of even numbers present in the array.
- Displays the total count of odd numbers present in the array.
import java.util.Scanner;
public class EvenOddArrayElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i, evenNumber = 0, oddNumber = 0;
int a[] = new int[5];
System.out.println("enter the number of elements :- ");
int n = sc.nextInt();
System.out.println("enter the elements :-");
for (i = 0; i < n; i++) {
a[i] = sc.nextInt();
if (a[i] % 2 == 0) {
evenNumber++;
} else {
oddNumber++;
}
}
System.out.println("Total numbers of even are :- " + evenNumber);
System.out.println("Total numbers of odd are :- " + oddNumber);
}
}
Output :-
enter the number of elements :-
3
enter the elements :-
25
45
80
Total numbers of even are :- 1
Total numbers of odd are :- 2
Check Even and Odd Numbers Using Java 8
import java.util.Arrays;
public class EvenOddCountStream {
public static void main(String[] args) {
int[] arr = {25, 45, 80};
long evenCount = Arrays.stream(arr)
.filter(n -> n % 2 == 0)
.count();
long oddCount = Arrays.stream(arr)
.filter(n -> n % 2 != 0)
.count();
System.out.println("Even Count: " + evenCount);
System.out.println("Odd Count: " + oddCount);
}
}
Here are some related Java 8 programs that will help you understand Stream API concepts better: