In this section, we will create a Java program to display odd numbers from 1 to 100. To learn the Java odd number program, you must have the basic knowledge of Java for loop and if statement.
We can use different Java loops to display odd numbers:
- Using Java for Loop
- Using nested-if Statement
- Using while Loop
Using Java for Loop
In the following example, we have declared a variable named number and initialized it with 100 (the limit to print the odd number). We have used a for loop that executes up to 100 times and for each iteration of i the if statement checks the number is odd or not. After printing each odd number, the value if i is increased by 1.
In order to check the number, we have divided the number by 2 if it leaves a remainder, the number is odd and the print statement prints that number.
DisplayOddNumbersExample1.java
Output:
Using nested-if Statement
The following program is slight different from the above program because we have defined a method that contains the logic to check odd number. Inside the method, we have used nested-if statement.
DisplayOddNumbersExample2.java
Output:
Using while Loop
In the following program, we have replaced the for loop with while loop.
DisplayOddNumbersExample3.java
Output: