๐ก Program Explanation:
In this program, the user enters a starting and ending number.
The program then checks each number in that range and prints the ones that are even (divisible by 2).
๐ง Java Code:
// Java Program to Print Even Numbers in a Given Range
import java.util.Scanner;
public class EvenNumbersInRange {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking input from the 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("\nEven numbers between " + start + " and " + end + " are:");
// Loop through the range
for (int i = start; i <= end; i++) {
// Check if the number is even
if (i % 2 == 0) {
System.out.print(i + " ");
}
}
sc.close();
}
}
๐งฎ Example Output:
Enter the starting number: 10
Enter the ending number: 20
Even numbers between 10 and 20 are:
10 12 14 16 18 20
๐️ Explanation:
-
Scanneris used to take user input. -
The
forloop iterates through the given range. -
The condition
i % 2 == 0checks if a number is even. -
If true, the number is printed.
✅ Key Points:
-
%(modulus) operator gives the remainder when dividing two numbers. -
Even numbers always leave a remainder of 0 when divided by 2.
-
You can easily modify this program to print odd numbers by changing the condition to
i % 2 != 0.
Comments
Post a Comment