Find The Sum Of Even Numbers In The Given Range In Java
This article will guide you through finding the sum of even numbers within a specified range in Java. You will learn how to accept user input for the range and iterate through numbers to identify and sum the even ones.
Problem Statement
Calculating the sum of even numbers within a given range is a common programming task. This often involves iterating through a sequence of numbers and applying a condition to identify even numbers before accumulating their sum.
Example
If the range is from 1 to 10, the even numbers are 2, 4, 6, 8, 10. Their sum is 30.
Background & Knowledge Prerequisites
To understand this article, you should have a basic understanding of:
- Java syntax (variables, data types, operators).
- Conditional statements (
if). - Looping constructs (
fororwhile). - User input using
Scanner.
Use Cases or Case Studies
- Data Analysis: Summing even-indexed elements in an array or even-valued data points.
- Game Development: Calculating scores based on even-numbered turns or events.
- Financial Calculations: Summing transactions that occur on even-numbered days.
- Educational Tools: Creating exercises for students to practice number theory concepts.
- Algorithm Practice: A fundamental problem for practicing loops and conditionals.
Solution Approaches
We will explore a common and efficient approach using a for loop.
Approach 1: Iterating and Checking for Even Numbers
This approach involves iterating through each number in the given range and using the modulo operator to check if the number is even. If it is, the number is added to a running total.
One-line summary: Iterate from the start to the end of the range, check if each number is even, and add it to the sum.
// Sum of Even Numbers in Range
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt the user to enter the start of the range
System.out.print("Enter the start of the range: ");
int start = scanner.nextInt();
// Step 3: Prompt the user to enter the end of the range
System.out.print("Enter the end of the range: ");
int end = scanner.nextInt();
// Step 4: Initialize a variable to store the sum of even numbers
int sumOfEvens = 0;
// Step 5: Loop through each number in the given range
for (int i = start; i <= end; i++) {
// Step 6: Check if the current number is even
// A number is even if it is perfectly divisible by 2 (remainder is 0)
if (i % 2 == 0) {
// Step 7: If the number is even, add it to the sum
sumOfEvens += i;
}
}
// Step 8: Print the final sum of even numbers
System.out.println("The sum of even numbers in the range " + start + " to " + end + " is: " + sumOfEvens);
// Step 9: Close the scanner to prevent resource leaks
scanner.close();
}
}
Sample output:
Enter the start of the range: 1
Enter the end of the range: 10
The sum of even numbers in the range 1 to 10 is: 30
Stepwise explanation for clarity:
ScannerInitialization: AScannerobject is created to read input from the console.- Get Range Start: The program prompts the user to enter the starting number of the range and stores it in the
startvariable. - Get Range End: The program prompts the user to enter the ending number of the range and stores it in the
endvariable. - Initialize Sum: A variable
sumOfEvensis initialized to0. This variable will accumulate the sum of all even numbers found. - Loop Through Range: A
forloop is used to iterate through every integer fromstarttoend(inclusive). - Check for Even: Inside the loop, an
ifstatement checks if the current numberiis even using the modulo operator (%). Ifi % 2 == 0, it meansiis perfectly divisible by 2, and thus it's an even number. - Add to Sum: If the number
iis even, it is added tosumOfEvens. - Print Result: After the loop finishes iterating through all numbers in the range, the final
sumOfEvensis printed to the console. - Close Scanner: The
scanner.close()method is called to release system resources associated with theScannerobject.
Conclusion
Finding the sum of even numbers within a given range is a fundamental programming exercise that demonstrates the use of loops and conditional statements. By iterating through the numbers and applying a simple check for evenness, we can efficiently calculate the desired sum.
Summary
- Problem: Calculate the sum of all even numbers within a user-defined range.
- Solution: Use a
forloop to iterate from the start to the end of the range. - Even Check: Inside the loop, use the modulo operator (
%) to determine if a number is even (number % 2 == 0). - Accumulation: Add even numbers to a running total.
- Input: Utilize the
Scannerclass to get the start and end of the range from the user.