The following program takes the value for n that is the max limit of n from the user. The program starts checking for odd numbers between this range 1 to n and it displays all the odd numbers lying within that range.
Before we start, click on the links below to have a proper working idea of for loop and if statement that this program uses.
Program to display the Odd Numbers within the range in Java
//display the odd number in java
import java.util.*;
public class DisplayOddNumbers
{
public static void main(String args[])
{
int n;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number: ");
n=sc.nextInt();
System.out.print("Odd Numbers between 1 to "+n+" are: ");
for (int i = 1; i <= n; i++)
{
// if the number is not divisible by 2 then it is even
if (i % 2 != 0)
{
System.out.print(i + " ");
}
}
}
}
Output:
Enter the number: 10
Odd Numbers between 1 to 10 are: 1 3 5 7 9