Counting the Number of Even and Odd Elements in an Array in Java
Understanding Even and Odd Count
This task involves counting the number of even and odd elements in an array.
We will explore three different methods to achieve this in Java.
Method 1: Using Loop
This method iterates through the array and counts even and odd elements.
public class EvenOddCount { public static void countEvenOdd(int[] arr) { int evenCount = 0, oddCount = 0; for (int num : arr) { if (num % 2 == 0) evenCount++; else oddCount++; } System.out.println("Even Count: " + evenCount + ", Odd Count: " + oddCount); } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8}; countEvenOdd(arr); } }
Even Count: 4, Odd Count: 4
Method 2: Using Recursion
This method counts even and odd numbers using recursion.
public class EvenOddRecursion { public static void countEvenOddRec(int[] arr, int index, int evenCount, int oddCount) { if (index == arr.length) { System.out.println("Even Count: " + evenCount + ", Odd Count: " + oddCount); return; } if (arr[index] % 2 == 0) evenCount++; else oddCount++; countEvenOddRec(arr, index + 1, evenCount, oddCount); } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8}; countEvenOddRec(arr, 0, 0, 0); } }
Even Count: 4, Odd Count: 4
Method 3: Using Streams
This method uses Java Streams to determine even and odd numbers.
import java.util.Arrays; public class EvenOddStream { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8}; long evenCount = Arrays.stream(arr).filter(num -> num % 2 == 0).count(); long oddCount = arr.length - evenCount; System.out.println("Even Count: " + evenCount + ", Odd Count: " + oddCount); } }
Even Count: 4, Odd Count: 4