Program Explanation
This Java program takes a range of numbers (for example, from 1 to 100) and calculates:
-
The sum of all even numbers in that range
-
The sum of all odd numbers in that range
It uses a simple loop and conditional statements to separate odd and even numbers.
💻 Java Code:
// Java Program to Find the Sum of Odd and Even Numbers in a Given Range
import java.util.Scanner;
public class SumOfOddEven {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking input from user
System.out.print("Enter the starting number of the range: ");
int start = sc.nextInt();
System.out.print("Enter the ending number of the range: ");
int end = sc.nextInt();
int sumEven = 0, sumOdd = 0;
// Loop through the range
for (int i = start; i <= end; i++) {
if (i % 2 == 0)
sumEven += i; // Even number
else
sumOdd += i; // Odd number
}
// Display results
System.out.println("Sum of Even Numbers: " + sumEven);
System.out.println("Sum of Odd Numbers: " + sumOdd);
sc.close();
}
}
🧠How It Works
-
The program asks for a starting and ending number.
-
It loops through every number in that range.
-
If a number is divisible by 2, it’s even — added to the even sum.
-
Otherwise, it’s odd — added to the odd sum.
-
Finally, both sums are displayed.
🧾 Example Output
Enter the starting number of the range: 1
Enter the ending number of the range: 10
Sum of Even Numbers: 30
Sum of Odd Numbers: 25
Comments
Post a Comment