Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..

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");    
  }
}

Result:

Original Array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Number of even elements in the array: 5

Number of odd elements in the array: 5

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java programming language Basic programs with examples

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a Java program to compute the square root of... >>
<< Write a Java program to swap the first and last el...