๐ป Java Program:
// Java Program to Print Odd Numbers in a Given Range
import java.util.Scanner;
public class OddNumberInRange {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking input from user
System.out.print("Enter the starting number: ");
int start = sc.nextInt();
System.out.print("Enter the ending number: ");
int end = sc.nextInt();
System.out.println("\nOdd numbers between " + start + " and " + end + " are:");
// Loop to print odd numbers
for (int i = start; i <= end; i++) {
if (i % 2 != 0) { // Check if number is not divisible by 2
System.out.print(i + " ");
}
}
sc.close();
}
}
๐ง Explanation:
-
Scanner class is used to take input from the user.
-
We take two numbers — start and end — as the range.
-
A for loop runs from start to end.
-
The if condition (
i % 2 != 0) checks whether a number is odd. -
If true, it prints the number.
๐ค Example Output:
Enter the starting number: 10
Enter the ending number: 25
Odd numbers between 10 and 25 are:
11 13 15 17 19 21 23 25
๐ Key Points for Beginners:
-
%is the modulus operator — it gives the remainder of a division. -
Odd numbers always give remainder 1 when divided by 2.
-
You can modify the range to print even numbers by changing the condition to
i % 2 == 0.
Comments
Post a Comment