Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Print Odd Numbers in Java

Show odd numbers from 1 to 99 in Java with a for loop and i += 2. The limit is 100, but the last printed value is 99 because the next step reaches 101.

BeginnerJava Loop ProgramsExample 3 of 25
print-odd-numbers.java
1public class Main {
2 public static void main(String[] args) {
3 for (int i = 1; i <= 100; i += 2) {
4 System.out.print(i + " ");
5 }
6 }
7}

Sample Output

1 3 5 ... 99

The loop visits 1, 3, 5, and so on. After 99, i becomes 101 and no further number prints.

In this one

  • Keep odd values with a step of two
  • Distinguish a limit from a printed endpoint
  • Count repeated loop passes

How it works

  1. 1

    Start i at 1.

  2. 2

    Print while i <= 100.

  3. 3

    Add 2 after each print.

  4. 4

    Stop when i becomes 101.

Edge cases

Even starting point

Start i at 2

The loop now produces even numbers, so the starting point is part of the logic.

Smaller limit

Set the limit to 1

Only the first number prints.

What's going on

Display the odd numbers from 1 up to 100. An odd whole number cannot be split into two equal whole-number groups. The last answer is 99, because 100 is not odd. This is a useful contrast with the even-number loop.

The for loop starts i at 1 and uses i += 2 to visit only odd values. Before each print it checks i <= 100. The space after each number makes the one-line output readable. There is no test inside the loop because the starting value and step already choose the right numbers.

After printing 99, the update makes i equal to 101, and the loop stops. The limit does not have to be a value that prints. A common mistake is starting at 2 and keeping the same update; that would produce the even list. Another is using i++ and forgetting that it visits both odd and even numbers.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is the last printed number?

Pick an answer to check it.

Question 2

Which update keeps this sequence odd?

Pick an answer to check it.

Questions people ask

Why does 100 not appear?

The sequence goes from 99 straight to 101. The condition does not force the endpoint to print.

Could I test each number instead?

Yes. You could visit every number and print it when its remainder after division by two is not zero.

How many odd values are printed?

50, starting at 1 and ending at 99.