Print Odd Numbers in Java
Problem
Odd numbers are every other integer starting from 1, so a loop can generate them directly by stepping by 2 instead of checking each number individually.
Given a number n, print every odd number from 1 up to n.
Java Program
public class PrintOddNumbers {
public static void main(String[] args) {
int n = 20;
for (int i = 1; i <= n; i += 2) {
System.out.println(i);
}
}
}Output
Core Logic
Starting the counter at 1 and stepping forward by 2 each time lands on every odd number directly, without ever visiting an even one.
- 1
for (int i = 1; i <= n; i += 2)starts at the first odd number and increases by2instead of1. - 2Because the step size is 2, every value
itakes on is already odd — there's no need to testi % 2 != 0inside the loop. - 3The loop stops once
ipassesn, so the highest printed value is the largest odd number that doesn't exceedn.
n = 20, the loop starts at 1 and lands on 3, 5, 7, and so on, up through 19 — 20 itself is even, so it's never reached.Key Point: Stepping by 2 from an odd starting point does half the work of a 1-to-n loop with a modulo check inside it, the same efficiency gain used for printing even numbers.
Why: The loop runs once per odd number in the range, a count proportional to n, printing one value each with no growing storage.
Key Concepts
Approach 2: Java 8
import java.util.stream.IntStream;
public class PrintOddNumbersStream {
public static void main(String[] args) {
int n = 20;
IntStream.rangeClosed(1, n).filter(i -> i % 2 != 0).forEach(System.out::println);
}
}
Output
Core Logic
Filtering a full 1-to-n stream down to the odd values expresses the same idea as a pipeline, at the cost of visiting the even numbers just to discard them.
- 1
IntStream.rangeClosed(1, n)generates every number in the range, both even and odd. - 2
.filter(i -> i % 2 != 0)keeps only the values not divisible by 2. - 3
.forEach(System.out::println)prints each surviving value in order.
n = 20, the filtered stream keeps 1, 3, 5, ..., 19 — the same ten values the step-by-2 loop produces.Key Point: Unlike the loop's step-by-2 technique, this version still generates and discards every even number along the way — a reasonable trade for how directly it reads as 'keep only the odd ones'.
Why: The stream visits all n numbers in the range to filter them, twice the work of stepping by 2 directly, though still linear in n.