Count odd or even numbers in Java


This program allows the user to enter the size of an array, and then prompts the user to enter n integer values. It then counts the number of even and odd integers in the array and prints the counts.

The program first declares two integer variables e and o and initializes them to zero. These variables will be used to keep track of the counts of even and odd integers in the array. The program then prompts the user to enter the size of the array n and creates an array a of n integers using the statement int a[] = new int[n]; .

The program then uses a for loop to prompt the user to enter n integer values for the array a. For each iteration of the loop, the program prompts the user to enter the value of the current element and assigns it to the appropriate element in the array.

The program then uses an enhanced for loop to iterate over each element in the array a. For each element, the program checks whether it is even or odd using the expression element % 2 == 0. If the element is even, the program increments the variable e. Otherwise, the program increments the variable o.

Finally, the program prints the counts of even and odd integers in the array using System.out.println().

Source Code

import java.util.Scanner;
 
public class even_odd {
    //Write a program to count even and odd numbers in an array
    public static void main(String[] args) {
        int e = 0, o = 0;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter The Limit : ");
        int n = in.nextInt();
        int a[] = new int[n];
        for (int i = 0; i < n; i++) {
            System.out.println("Enter a[" + i + "] value : ");
            a[i] = in.nextInt();
        }
        for (int element : a) {
            if (element % 2 == 0) {
                e++;
            } else {
                o++;
            }
        }
        System.out.println("Total Even Nos : " + e);
        System.out.println("Total Odd Nos  : " + o);
    }
}

Output

Enter The Limit :
5
Enter a[0] value :
10
Enter a[1] value :
34
Enter a[2] value :
53
Enter a[3] value :
41
Enter a[4] value :
45
Total Even Nos : 2
Total Odd Nos  : 3
To download raw file Click Here

Basic Programs