In this tutorial, we will learn how to write a Java program to find the sum of even numbers up to N. Given a positive integer N, the program calculates the sum of all even numbers in the range 1 to N (inclusive).
For example, if the user enters 10 as the value of N, the program will calculate the sum of all even numbers from 1 to 10 as follows:
2 + 4 + 6 + 8 + 10 = 30
Therefore, the sum of even numbers up to 10 is 30.
We will cover the following approaches to calculate the sum of even numbers in Java:
- Using a for loop
- Using a while loop
- Using a mathematical formula
Let’s start with the first approach: using a for loop.
Java Program to Find the Sum of Even Numbers up to N Using for Loop
The for loop is one of the simplest ways to calculate the sum of even numbers in Java. In this approach, we initialize a variable named sum with 0 and use a for loop to generate even numbers starting from 2.
Inside the loop, we add the current even number to the sum variable. We increase the loop variable by 2 after every iteration so that the loop processes only even numbers.
Let’s write a complete Java program to calculate the sum of even numbers up to N using a for loop.
Java Program
import java.util.Scanner;
public class SumOfEvenNumbers {
public static void main(String[] args) {
// Create a Scanner object to read input.
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the value of N.
System.out.print("Enter the value of N: ");
int n = scanner.nextInt();
// Initialize the sum variable with 0.
long sum = 0;
// Check whether the input is valid or not.
if (n >= 1) {
// Calculate the sum of even numbers using for loop.
for (long i = 2; i <= n; i += 2) {
sum = sum + i;
}
// Display the calculated sum.
System.out.println("Sum of even numbers up to " + n + " is: " + sum);
} else {
System.out.println("Please enter a positive integer.");
}
// Close the Scanner.
scanner.close();
}
}Expected Output:
Enter the value of N: 10 Sum of even numbers up to 10 is: 30
Explanation of the Java Program
Let’s understand how this Java program works step by step.
- Import the Scanner class: First, we import
Scanner classfrom the java.util package to accept input from the keyboard. - Create a Scanner object: We create an object of the Scanner class to read the integer number entered by the user.
- Read the value of N: We use the nextInt() method to read the input and store it in the variable named n.
- Initialize the sum variable: We declare a variable named sum of type long and initialize it with 0. This variable stores the running total of even numbers.
- Validate the input: We use an if statement to check whether the entered number is greater than or equal to 1.
- Initialize the loop variable: Inside the for loop, we initialize the variable i with 2 because 2 is the first positive even number.
- Check the loop condition: The condition
i <= nensures that the loop executes only while the current even number is less than or equal to N. - Calculate the sum: The statement
sum = sum + iadds the current even number to the previous sum. - Increase the loop variable: The expression
i += 2increases the value of i by 2 after every iteration to generate the next even number. - Display the result: Finally, we print the calculated sum on the console using the statement
System.out.println().
Thus, the above program calculates the sum of all positive even numbers from 2 up to N.
Execution of the Java Program
Let’s understand the execution of the for loop by taking N = 10. Initially, the value of variable sum is 0, and the loop variable i starts from 2.
| Iteration | Value of i | Calculation | Sum |
|---|---|---|---|
| 1 | 2 | 0 + 2 | 2 |
| 2 | 4 | 2 + 4 | 6 |
| 3 | 6 | 6 + 6 | 12 |
| 4 | 8 | 12 + 8 | 20 |
| 5 | 10 | 20 + 10 | 30 |
After the fifth iteration, the value of i becomes 12. Since the condition i <= 10 becomes false, the loop terminates. Therefore, the final sum is 30.
Java Program to Find the Sum of Even Numbers Using while Loop
To calculate the sum of even numbers up to N, we can also use a while loop in Java. A while loop repeatedly executes a block of statements as long as its specified condition evaluates to true.
In this approach, we initialize a variable i with 2 and a variable sum with 0 before the loop starts. Inside the while loop, we add the current value of i to sum and increase the value of i by 2.
Let’s write the complete Java program to find the sum of all even numbers using while loop.
Java Program
import java.util.Scanner;
public class SumEvenNumbersWhile {
public static void main(String[] args) {
// Create a Scanner object to read input from standard input.
Scanner scanner = new Scanner(System.in);
// Prompt the user and read the upper limit N.
System.out.print("Enter the value of N: ");
int n = scanner.nextInt();
// Use long for sum to prevent integer overflow for larger values of N.
long sum = 0;
// Start from the first positive even number.
int i = 2;
// Validate that N is a positive integer.
if (n >= 1) {
// Add even numbers from 2 up to N (inclusive) using a while loop.
while (i <= n) {
sum += i; // Equivalent to sum = sum + i
i += 2; // Jump directly to the next even number
}
// Print the final calculated sum.
System.out.println("Sum of even numbers up to " + n + " is: " + sum);
} else {
// Handle zero or negative inputs.
System.out.println("Please enter a positive integer.");
}
// Close the Scanner to release the input stream resource.
scanner.close();
}
}Expected Output:
Enter the value of N: 15 Sum of even numbers up to 15 is: 56
Mathematical Formula to Find the Sum of Even Numbers up to N
We can also calculate the sum of even numbers up to N directly using a mathematical formula without executing a loop. The positive even numbers are:
2, 4, 6, 8, 10, ..., 2k
Here, k represents the number of positive even numbers up to N.
The mathematical formula is:
Sum = k × (k + 1)
Where:
- k represents the number of positive even numbers up to N.
- Sum represents the total of all positive even numbers from 2 to N.
We can calculate the value of k using:
k = N / 2
Here, integer division is used, which automatically ignores the fractional part. Therefore, the complete formula is:
Sum = (N / 2) × ((N / 2) + 1)
For example, if the value of N = 10:
k = 10 / 2 k = 5 Sum = 5 × (5 + 1) Sum = 5 × 6 Sum = 30
Therefore, the sum of even numbers up to 10 is 30.
Note: If the value of N is odd, the mathematical formula still works because integer division gives the number of positive even numbers within the range.
For example, if N = 9:
k = 9 / 2 k = 4 Sum = 4 × (4 + 1) Sum = 4 × 5 Sum = 20
Therefore, the sum of even numbers up to 9 is 20.
Let’s write a Java program to calculate the sum of even numbers up to N using the mathematical formula.
Java Program
import java.util.Scanner;
public class SumEvenNumbersFormula {
public static void main(String[] args) {
// Create a Scanner object to read input from standard input.
Scanner scanner = new Scanner(System.in);
// Prompt the user and read the value of N.
System.out.print("Enter the value of N: ");
int n = scanner.nextInt();
// Validate that N is a positive integer.
if (n >= 1) {
// Count how many positive even numbers exist up to N using integer division.
long k = n / 2;
// Apply the arithmetic series formula k * (k + 1) in O(1) constant time.
long sum = k * (k + 1);
// Print the final calculated sum.
System.out.println("Sum of even numbers up to " + n + " is: " + sum);
} else {
// Handle zero or negative inputs.
System.out.println("Please enter a positive integer.");
}
// Close the Scanner to release the input stream resource.
scanner.close();
}
}Expected Output:
Enter the value of N: 20 Sum of even numbers up to 20 is: 110
In this program, we first calculate the number of positive even numbers using the expression n / 2. Then, we apply the mathematical formula k * (k + 1) to calculate their sum.
Why Do We Use long Instead of int?
The sum of even numbers can grow larger than the maximum value of a signed 32-bit int in Java, which is 2,147,483,647 (Integer.MAX_VALUE). For example, when N = 100,000, the sum is 2,500,050,000, which causes integer overflow in an int.
A signed 64-bit long holds values up to 9,223,372,036,854,775,807 (Long.MAX_VALUE), making it safe for much larger inputs. Therefore, we use long to store the calculated sum and the loop variable to avoid integer overflow in these examples.
Which Approach Is Better to Find the Sum of Even Numbers in Java?
We can use different approaches to calculate the sum of even numbers in Java. However, the best approach depends on the requirements of the program.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| for loop | O(N) | O(1) |
| while loop | O(N) | O(1) |
| Mathematical formula | O(1) | O(1) |
The mathematical formula is the most efficient approach because it calculates the sum of even numbers directly without executing a loop.
However, using a for loop or while loop is helpful for beginners who want to understand loop execution and accumulation in Java programming.


