Sum of Odd Numbers in Java
Problem
Stepping through only the odd numbers and accumulating them one at a time totals up the odd half of the sequence directly.
Given a number n, find the sum of every odd number from 1 up to n.
Java Program
public class SumOfOddNumbers {
public static void main(String[] args) {
int n = 20;
int sum = 0;
for (int i = 1; i <= n; i += 2) {
sum += i;
}
System.out.println("Sum of odd numbers: " + sum);
}
}Output
Core Logic
Starting at 1 and stepping forward by 2 each time visits only the odd numbers, adding each one into a running total as it goes.
- 1
sumstarts at0, before any number has been added. - 2
for (int i = 1; i <= n; i += 2)visits every odd number from 1 up ton, the same stepping technique used to print them. - 3Each iteration adds the current
iintosum. - 4Once the loop finishes,
sumholds the total of every odd number visited.
n = 20, the loop adds 1, 3, 5, ..., 19 into sum, accumulating to 100 — 20 itself is even and never visited.Key Point: Stepping by 2 from an odd start keeps the even 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 odd 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 SumOfOddNumbersStream {
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 odd numbers: " + sum);
}
}
Output
Core Logic
Filtering a full 1-to-n stream down to the odd 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 not divisible by 2. - 3
.sum()reduces the filtered stream down to a single total.
n = 20, the filtered stream keeps 1, 3, ..., 19, and sum() reports the same total, 100.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.