w3resource

Java: Find the number of even and odd integers in a given array of integers

Java Array: Exercise-27 with Solution

Write a Java program to find the number of even and odd integers in a given array of integers.

Pictorial Presentation:

Java Array Exercises: Find the number of even and odd integers in a given array of integers

Sample Solution:

Java Code:

// Import the java.util package to use utility classes, including Arrays.
import java.util.Arrays;

// Define a class named Exercise27.
public class Exercise27 {
    // The main method for executing the program.
    public static void main(String[] args) {
        // Declare and initialize an array of integers.
        int[] array_nums = {5, 7, 2, 4, 9};

        // Print the original array.
        System.out.println("Original Array: " + Arrays.toString(array_nums));

        // Initialize a counter variable for even numbers.
        int ctr = 0;

        // Use a loop to iterate through the array elements and count even numbers.
        for (int i = 0; i < array_nums.length; i++) {
            if (array_nums[i] % 2 == 0)
                ctr++;
        }

        // Print the number of even and odd numbers in the array.
        System.out.println("Number of even numbers : " + ctr);
        System.out.println("Number of odd numbers  : " + (array_nums.length - ctr));
    }
}

Sample Output:

                                                                              
Original Array: [5, 7, 2, 4, 9]                                        
Number of even numbers : 2                                             
Number of odd numbers  : 3 

Flowchart:

Flowchart: Java exercises: Find the number of even and odd integers in a given array of integers

Java Code Editor:

Previous: Write a Java program to move all 0's to the end of an array.
Next: Write a Java program to get the difference between the largest and smallest values in an array of integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/array/java-array-exercise-27.php