Java Program to Display Odd Numbers From 1 to 100In 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 LoopIn 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: List of odd numbers from 1 to 100: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 Using nested-if StatementThe 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: List of odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 Using while LoopIn the following program, we have replaced the for loop with while loop. DisplayOddNumbersExample3.java Output: Enter the limit: 100 Lit of odd numbers: 1 3 5 7 9 11 15 17 13 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 83 81 85 87 89 91 93 95 97 99 Next TopicJava Programs |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India