Count Odd Elements in an Array in Java
Problem
An odd number is any integer that leaves a remainder of 1 (or -1) when divided by 2.
Given an array of integers, count how many of its elements are odd.
Java Program
public class CountOdd {
public static void main(String[] args) {
int[] arr = {4, 7, 10, 15, 22, 33, 8};
int count = 0;
for (int num : arr) {
if (num % 2 != 0) count++; // not divisible by 2
}
System.out.println("Odd elements: " + count);
}
}Output
Core Logic
A single pass through the array, checking each number's remainder when divided by 2, tallies every odd value.
- 1A for-each loop visits each element of the array in turn.
- 2
num % 2 != 0checks whether the current number does NOT divide evenly by 2. - 3A match increments the
countvariable; anything else is skipped. - 4After the loop,
countholds the total number of odd elements.
[4, 7, 10, 15, 22, 33, 8], the scan finds 7, 15, and 33 — three odd elements.Key Point: Using != 0 rather than == 1 matters for negative odd numbers — in Java, -7 % 2 evaluates to -1, not 1, so checking for exactly 1 would miss it.
Why: Each element is visited once, and only a single running counter is kept regardless of array size.
Key Concepts
Approach 2: Java 8
import java.util.Arrays;
public class CountOddStream {
public static void main(String[] args) {
int[] arr = {4, 7, 10, 15, 22, 33, 8};
// filter() keeps only odd values; count() reduces to a single total
long count = Arrays.stream(arr).filter(num -> num % 2 != 0).count();
System.out.println("Odd elements: " + count);
}
}
Output
Core Logic
The same divisibility check can filter a stream of the array's values down to just the odd ones, then count what's left.
- 1
Arrays.stream(arr)converts theint[]into anIntStream. - 2
.filter(num -> num % 2 != 0)keeps only the values NOT divisible by 2. - 3
.count()reduces the filtered stream down to a singlelongtotal.
[4, 7, 10, 15, 22, 33, 8] keeps 7, 15, 33, so count() returns 3.Key Point: Flipping == 0 to != 0 is the only change needed to turn the even-counting stream into this one — the rest of the pipeline stays identical.
Why: The stream still visits every element once, and count() reduces straight down to a single long without collecting anything.