Java Program to Display Odd Number


In this post, we will learn, How to write a program to display odd numbers based on given user input. 

Before moving to the programming part, Let's try to understand, What is an odd number?
Odd Number:- Any number which are not divisible by 2, Or any number which are not equally divided into two parts. Ex:- 1,3,5,7,9,11,13,15,17,19 ..... 

Now, Let's jump into programming part
We will use two different way to take the input from users and achieve the expected output
  1. Use predefined variable value in the program.
  2. Take user input at runtime.

1. Use predefined variable value in the program

Code:


public class OddNumberProgram {


public static void main(String[] args) {

int numberRange = 30;

System.out.println("Printing the odd numbers......");

for(int i=1; i<=numberRange; i++) {

if(i%2 != 0)

System.out.println(i);

}

}

}

Output:- 

1,3,5,7,9,11,13,15,17,19,21,23,25,27,29


Steps Explanation:-

  1. Define integer variable with having value 30; 
  2. Start for loop with initial iteration from 1 to defined input range.
  3. Applied if loop with checking the iterated number should not having the reminder 0.
  4. Then print the iterated number. 

2. Take user input at runtime

Code:


public class OddNumberProgram {


public static void main(String[] args) {

                Syetem.out.println("Enter the number to find odd number ");

                Scanner  scanner = new Scanner(System.in);

int numberRange = scanner.nextInt();

System.out.println("Printing the odd numbers......");

for(int i=1; i<=numberRangei++) {

if(i%2 != 0)

System.out.println(i);

}

}

}


Output:- 

Enter the number to find odd number 

30

Printing the odd numbers......

1,3,5,7,9,11,13,15,17,19,21,23,25,27,29


Steps Explanations:-

  1. Created object of Scanner class. 
  2. Store System input value into numberRange variable by calling the nextInt() method.
  3. Start for loop with initial iteration from 1 to defined input range.
  4. Applied if loop with checking the iterated number should not have the reminder 0.
  5. Then print the iterated number. 
I hope this post helps you ..........................

Post a Comment

Previous Post Next Post