Count Number Of Even And Odd Elements In An Array In Java
Counting the number of even and odd elements in an array is a fundamental programming task, often used to introduce concepts of iteration and conditional logic. In this article, you will learn how to efficiently determine the counts of even and odd numbers within a Java array using several common approaches.
Problem Statement
The core problem involves iterating through a given array of integer numbers and, for each number, checking if it is even or odd. Based on this check, a counter for even numbers or a counter for odd numbers is incremented. This task is crucial for data analysis, filtering, and understanding data distributions within collections.
Example
Consider the following integer array as input:
int[] numbers = {12, 7, 24, 15, 30, 9, 10};
After processing, the expected output for this array would be:
- Even numbers: 4 (12, 24, 30, 10)
- Odd numbers: 3 (7, 15, 9)
Background & Knowledge Prerequisites
To understand the solutions presented in this article, readers should have a basic understanding of the following Java concepts:
- Variables: Declaring and assigning values to integer variables.
- Arrays: How to declare, initialize, and access elements of an array.
- Loops: Basic
forloops andfor-eachloops for iteration. - Conditional Statements:
if-elsestatements. - Modulo Operator (
%): Understanding hownumber % 2 == 0determines if a number is even.
No specific imports beyond standard Java libraries are required for the basic approaches.
Use Cases or Case Studies
Counting even and odd elements in an array has several practical applications across various domains:
- Data Analysis: In statistics, separating data points into categories (e.g., even/odd IDs, even/odd scores) for further analysis or visualization.
- Game Development: Determining the number of even-numbered levels completed or odd-numbered items collected.
- Resource Allocation: In scenarios where resources are indexed numerically, categorizing them based on even/odd IDs to balance distribution.
- Algorithm Design: As a preliminary step in more complex algorithms that require processing different types of numbers separately.
- Educational Tools: A common exercise for beginners to grasp array traversal, conditional logic, and basic arithmetic operations in programming.
Solution Approaches
Here are three common approaches to count even and odd elements in a Java array.
Approach 1: Using a for loop (Iterative Approach)
This approach uses a traditional for loop to iterate through the array by index, checking each element.
// CountEvenOddForLoop
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Declare and initialize the array
int[] numbers = {12, 7, 24, 15, 30, 9, 10, 5, 22};
// Step 2: Initialize counters for even and odd numbers
int evenCount = 0;
int oddCount = 0;
// Step 3: Iterate through the array using a traditional for loop
for (int i = 0; i < numbers.length; i++) {
// Step 4: Check if the current element is even or odd
if (numbers[i] % 2 == 0) {
evenCount++; // Increment even counter if even
} else {
oddCount++; // Increment odd counter if odd
}
}
// Step 5: Print the results
System.out.println("Array elements: " + java.util.Arrays.toString(numbers));
System.out.println("Number of Even Elements: " + evenCount);
System.out.println("Number of Odd Elements: " + oddCount);
}
}
Sample Output:
Array elements: [12, 7, 24, 15, 30, 9, 10, 5, 22]
Number of Even Elements: 6
Number of Odd Elements: 3
Stepwise Explanation:
- Array Initialization: An integer array
numbersis declared and populated with sample values. - Counter Initialization: Two integer variables,
evenCountandoddCount, are initialized to0. These will store the final counts. - Loop Iteration: A
forloop is used to iterate from index0up to (but not including) the length of thenumbersarray. This ensures every element is visited. - Even/Odd Check: Inside the loop, for each element
numbers[i], the modulo operator (%) is used. Ifnumbers[i] % 2is0, the number is even, andevenCountis incremented. Otherwise, the number is odd, andoddCountis incremented. - Print Results: After the loop completes, the final
evenCountandoddCountare printed to the console.
Approach 2: Using a for-each loop (Enhanced For Loop)
The for-each loop provides a more concise way to iterate over elements in an array when the index is not needed.
// CountEvenOddForEachLoop
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Declare and initialize the array
int[] numbers = {4, 1, 8, 3, 10, 6, 9};
// Step 2: Initialize counters for even and odd numbers
int evenCount = 0;
int oddCount = 0;
// Step 3: Iterate through the array using an enhanced for loop (for-each)
for (int number : numbers) {
// Step 4: Check if the current element is even or odd
if (number % 2 == 0) {
evenCount++; // Increment even counter if even
} else {
oddCount++; // Increment odd counter if odd
}
}
// Step 5: Print the results
System.out.println("Array elements: " + java.util.Arrays.toString(numbers));
System.out.println("Number of Even Elements: " + evenCount);
System.out.println("Number of Odd Elements: " + oddCount);
}
}
Sample Output:
Array elements: [4, 1, 8, 3, 10, 6, 9]
Number of Even Elements: 4
Number of Odd Elements: 3
Stepwise Explanation:
- Array Initialization: Similar to Approach 1, an integer array
numbersis initialized. - Counter Initialization:
evenCountandoddCountare set to0. - Enhanced Loop Iteration: A
for-eachloop (for (int number : numbers)) iterates through eachnumberdirectly from thenumbersarray. This eliminates the need to manage an explicit index. - Even/Odd Check: Inside the loop, the current
numberis checked using the modulo operator.evenCountoroddCountis incremented accordingly. - Print Results: The final counts are displayed.
Approach 3: Using Java Streams (Functional Approach)
For more modern Java development (Java 8 and later), streams offer a functional and often more concise way to process collections.
// CountEvenOddJavaStreams
import java.util.Arrays;
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Declare and initialize the array
int[] numbers = {2, 5, 11, 14, 17, 20, 23};
// Step 2: Use streams to count even numbers
long evenCount = Arrays.stream(numbers)
.filter(n -> n % 2 == 0) // Filter for even numbers
.count(); // Count the filtered elements
// Step 3: Use streams to count odd numbers
long oddCount = Arrays.stream(numbers)
.filter(n -> n % 2 != 0) // Filter for odd numbers
.count(); // Count the filtered elements
// Step 4: Print the results
System.out.println("Array elements: " + Arrays.toString(numbers));
System.out.println("Number of Even Elements: " + evenCount);
System.out.println("Number of Odd Elements: " + oddCount);
}
}
Sample Output:
Array elements: [2, 5, 11, 14, 17, 20, 23]
Number of Even Elements: 3
Number of Odd Elements: 4
Stepwise Explanation:
- Array Initialization: An integer array
numbersis declared and populated. - Count Even Numbers:
-
Arrays.stream(numbers): Converts theintarray into anIntStream. -
.filter(n -> n % 2 == 0): This is an intermediate operation that filters the stream, keeping only elements for which the lambda expressionn % 2 == 0evaluates totrue(i.e., even numbers). -
.count(): This is a terminal operation that counts the number of elements remaining in the filtered stream. The result is along.
- Count Odd Numbers: This step is similar to counting even numbers, but the
filtercondition is changed ton % 2 != 0to select odd numbers. - Print Results: The computed
evenCountandoddCount(which arelongdue to thecount()method) are printed.
Conclusion
Counting even and odd elements in a Java array is a straightforward task that can be accomplished using several methods, each with its own advantages. The traditional for loop offers granular control and is ideal for beginners, while the for-each loop provides a cleaner syntax for simple iteration. For more advanced scenarios and to leverage functional programming paradigms, Java Streams offer a concise and expressive way to perform such operations. Choosing the right approach depends on readability preferences, performance considerations, and the specific Java version being used.
Summary
- Problem: Determine the count of even and odd numbers within an integer array.
- Modulo Operator: The key to checking even/odd is
number % 2 == 0(even) ornumber % 2 != 0(odd). - Traditional
forloop: Iterates by index, offering explicit control over array elements. -
for-eachloop: Simplifies iteration when array indices are not explicitly needed, improving readability. - Java Streams (Java 8+): Provides a functional and declarative way to filter and count elements, often resulting in more concise code.