Java Program to Count Even and Odd Elements in Array

Java Program to Count Even and Odd Elements in Array

In this tutorial, we are going to learn to write a java program to count the total even and the odd number present in an array.

There are multiple ways to write this program either we can take the array as input from the users or we can manually provide the array.

  • To count the even and odd numbers in the array, we will be using the if else statement.
  • Also, we have two variables evenCount and oldCount to record the count of even and odd.
  • To identify an even number, we will be using the logic if(i%2==0), means that the number divided by two should return zero to become an even number.
  • And the number that is not fully divided by zero is an odd number.
  • For each satisfied condition in an if-else block, we are increasing the count of the respective variable.

Program 1: Java Program to Count the even and odd numbers present in an Array

import java.util.*;
class Main{
    public static void main(String ...a){
        int arr[] = new int[]{ 1,2,3,4,5,6,7,8,9,10,11 }; 
        int evenCount=0, oddCount=0;
        for(int i=0; i<arr.length;i++){
            if(arr[i]%2==0){
                evenCount++;
            }else{
                oddCount++;
            }
        }
        System.out.println("Total Even Number : " + evenCount + "\nTotal Odd Number : "+oddCount);
    }
}

Output

count even odd array java

Program 2: Java Program to Count the even and odd numbers present in an Array

The logic of the below program is very similar to the above, Only the change is here we have a dynamic array. We are taking the size of the array and array elements at the run time from users.

import java.util.*;
class Main{
    public static void main(String ...a){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the size of array: ");
        int n = sc.nextInt();
        int arr[] = new int[n];
        System.out.println("Enter " +(n)+ " array elements: ");
        for(int i=0; i<n; i++) {
            arr[i] = sc.nextInt();
        } 
        int evenCount=0, oddCount=0;
        for(int i=0; i<arr.length;i++){
            if(arr[i]%2==0){
                evenCount++;
            }else{
                oddCount++;
            }
        }
        System.out.println("Total Even Number : " + evenCount + "\nTotal Odd Number : "+oddCount);
    }
}

Output