Sum of Even Numbers in Java
Problem
Stepping through only the even numbers and accumulating them one at a time totals up the even half of the sequence directly.
Given a number n, find the sum of every even number from 2 up to n.
Java Program
public class SumOfEvenNumbers {
public static void main(String[] args) {
int n = 20;
int sum = 0;
for (int i = 2; i <= n; i += 2) {
sum += i;
}
System.out.println("Sum of even numbers: " + sum);
}
}Output
Core Logic
Starting at 2 and stepping forward by 2 each time visits only the even numbers, adding each one into a running total as it goes.
- 1
sumstarts at0, before any number has been added. - 2
for (int i = 2; i <= n; i += 2)visits every even number from 2 ton, the same stepping technique used to print them. - 3Each iteration adds the current
iintosum. - 4Once the loop finishes,
sumholds the total of every even number visited.
n = 20, the loop adds 2, 4, 6, ..., 20 into sum, accumulating to 110.Key Point: Stepping by 2 keeps the odd numbers out of the loop entirely — there's no need for a modulo check inside the loop to filter them out.
Why: The loop adds one number into the running total per even number in the range, a count proportional to n, with only a single accumulator kept.
Key Concepts
Approach 2: Java 8
import java.util.stream.IntStream;
public class SumOfEvenNumbersStream {
public static void main(String[] args) {
int n = 20;
int sum = IntStream.rangeClosed(1, n).filter(i -> i % 2 == 0).sum();
System.out.println("Sum of even numbers: " + sum);
}
}
Output
Core Logic
Filtering a full 1-to-n stream down to the even values, then reducing them to a total, expresses the same sum as a pipeline.
- 1
IntStream.rangeClosed(1, n)generates every number in the range, both even and odd. - 2
.filter(i -> i % 2 == 0)keeps only the values divisible by 2. - 3
.sum()reduces the filtered stream down to a single total.
n = 20, the filtered stream keeps 2, 4, ..., 20, and sum() reports the same total, 110.Key Point: sum() reduces straight to a single int without ever collecting the filtered values into a list — it tallies as it filters, the stream equivalent of the loop's running accumulator.
Why: The stream visits all n numbers in the range to filter them, and sum() reduces to a single total without collecting anything.