- Use predefined variable value in the program.
- 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:-
- Define integer variable with having value 30;
- Start for loop with initial iteration from 1 to defined input range.
- Applied if loop with checking the iterated number should not having the reminder 0.
- 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<=numberRange; i++) {
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:-
- Created object of Scanner class.
- Store System input value into numberRange variable by calling the nextInt() method.
- Start for loop with initial iteration from 1 to defined input range.
- Applied if loop with checking the iterated number should not have the reminder 0.
- Then print the iterated number.
Post a Comment