Java ProgramsControl FlowSum of Even Numbers

Sum of Even Numbers in Java

beginner·  Control Flow  ·  Loops

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.

Input
n = 20
Output
Sum of even numbers: 110

Java Program

Java
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

Sum of even numbers: 110

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.

How It Works
  1. 1sum starts at 0, before any number has been added.
  2. 2for (int i = 2; i <= n; i += 2) visits every even number from 2 to n, the same stepping technique used to print them.
  3. 3Each iteration adds the current i into sum.
  4. 4Once the loop finishes, sum holds the total of every even number visited.
For 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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

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

for loopstep incrementaccumulator variable

Approach 2: Java 8

Java
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

Sum of even numbers: 110

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.

How It Works
  1. 1IntStream.rangeClosed(1, n) generates every number in the range, both even and odd.
  2. 2.filter(i -> i % 2 == 0) keeps only the values divisible by 2.
  3. 3.sum() reduces the filtered stream down to a single total.
For 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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

Why: The stream visits all n numbers in the range to filter them, and sum() reduces to a single total without collecting anything.

Key Concepts

StreamIntStream.rangeClosed()filter()sum()

Related Programs