Java Program to Print Odd Numbers from 1 to n
for loop from 1 to n and print numbers where i % 2 != 0, like for (int i = 1; i <= n; i++) { if (i % 2 != 0) System.out.println(i); }.Examples
How to Think About It
Algorithm
Code
public class OddNumbers { public static void main(String[] args) { int n = 10; // You can change this value for (int i = 1; i <= n; i++) { if (i % 2 != 0) { System.out.println(i); } } } }
Dry Run
Let's trace the program with n = 5 to see how it prints odd numbers.
Start loop with i = 1
Check if 1 % 2 != 0 (true), print 1
Next i = 2
Check if 2 % 2 != 0 (false), do not print
Next i = 3
Check if 3 % 2 != 0 (true), print 3
Next i = 4
Check if 4 % 2 != 0 (false), do not print
Next i = 5
Check if 5 % 2 != 0 (true), print 5
| i | i % 2 != 0 | Printed |
|---|---|---|
| 1 | true | 1 |
| 2 | false | |
| 3 | true | 3 |
| 4 | false | |
| 5 | true | 5 |
Why This Works
Step 1: Loop from 1 to n
The program uses a for loop to go through every number starting at 1 up to n.
Step 2: Check if number is odd
It uses the condition i % 2 != 0 to find odd numbers because odd numbers leave a remainder of 1 when divided by 2.
Step 3: Print odd numbers
When the condition is true, the program prints the number, showing only odd numbers from 1 to n.
Alternative Approaches
public class OddNumbers { public static void main(String[] args) { int n = 10; for (int i = 1; i <= n; i += 2) { System.out.println(i); } } }
public class OddNumbers { public static void main(String[] args) { int n = 10; int i = 1; while (i <= n) { if (i % 2 != 0) { System.out.println(i); } i++; } } }
Complexity: O(n) time, O(1) space
Time Complexity
The program runs a loop from 1 to n, checking each number once, so it takes linear time O(n).
Space Complexity
It uses only a few variables and prints directly, so space used is constant O(1).
Which Approach is Fastest?
Incrementing by 2 is faster because it skips even numbers, reducing the number of iterations roughly by half.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Check each number with % operator | O(n) | O(1) | Simple and clear logic |
| Increment by 2 starting from 1 | O(n/2) | O(1) | More efficient, fewer iterations |
| While loop with condition | O(n) | O(1) | When loop control needs flexibility |
i += 2 starting from 1 to print odd numbers more efficiently.i % 2 != 0 and print all numbers instead of only odd ones.