Java Online Compiler
Example: CountEvenOddForEachLoop in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// 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); } }
Output
Clear
ADVERTISEMENTS