You are here: Home / Topics / Java program to count the number of even and odd elements in a given array

Java program to count the number of even and odd elements in a given array

Filed under: Java on 2024-03-05 21:30:40

This program will give you the logic of the same.

import java.util.*; 
public class Javaexcercise {
public static void main(String[] args)
{
   int[] nums = {1,2,3,4,5,6,7,8,9,10};
   int ctreven = 0, ctrodd = 0;
   System.out.println("Original Array: "+Arrays.toString(nums)); 

   for(int i = 0; i < nums.length; i++) {
       if(nums[i] % 2 == 0)
       {         
         ctreven++;
       }
       else
          ctrodd++;    
   }                 
   System.out.printf("\nNumber of even elements in the array: %d",ctreven);
   System.out.printf("\nNumber of odd elements in the array: %d",ctrodd);
   System.out.printf("\n");    
 }
}

About Author:
S
Shyam Dubey     View Profile
If you are good in any field. Just share your knowledge with others.