Java ProgramsControl FlowSum of Odd Numbers

Sum of Odd Numbers in Java

beginner·  Control Flow  ·  Loops

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.

Input
n = 20
Output
Sum of odd numbers: 100

Java Program

Java
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

Sum of odd numbers: 100

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.

How It Works
  1. 1sum starts at 0, before any number has been added.
  2. 2for (int i = 1; i <= n; i += 2) visits every odd number from 1 up 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 odd number visited.
For 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.

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

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

for loopstep incrementaccumulator variable

Approach 2: Java 8

Java
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

Sum of odd numbers: 100

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.

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 not divisible by 2.
  3. 3.sum() reduces the filtered stream down to a single total.
For 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.

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