Java ProgramsControl FlowPrint Odd Numbers

Print Odd Numbers in Java

beginner·  Control Flow  ·  Loops

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.

Input
n = 20
Output
1 3 5 7 9 11 13 15 17 19

Java Program

Java
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

1 3 5 7 9 11 13 15 17 19

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.

How It Works
  1. 1for (int i = 1; i <= n; i += 2) starts at the first odd number and increases by 2 instead of 1.
  2. 2Because the step size is 2, every value i takes on is already odd — there's no need to test i % 2 != 0 inside the loop.
  3. 3The loop stops once i passes n, so the highest printed value is the largest odd number that doesn't exceed n.
For 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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

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

for loopstep incrementodd numbers

Approach 2: Java 8

Java
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

1 3 5 7 9 11 13 15 17 19

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.

How It Works
  1. 1IntStream.rangeClosed(1, n) generates every number in the range, both even and odd.
  2. 2.filter(i -> i % 2 != 0) keeps only the values not divisible by 2.
  3. 3.forEach(System.out::println) prints each surviving value in order.
For 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'.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

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.

Key Concepts

StreamIntStream.rangeClosed()filter()

Related Programs