Java Lesson — While Loops, Nested While Loops, and Summation of Series

A full lesson from level zero to advanced, with special focus on summation of series.

What this lesson covers

In this lesson, you will learn how while loops work, how nested while loops work, and how these loops are used to calculate many kinds of mathematical series. We will begin with the simplest while loops, then move to summing natural numbers, even numbers, odd numbers, squares, cubes, harmonic-like expressions, factorial-based terms, and nested summations.

This lesson mainly concentrates on summation of series, because loops are one of the most natural tools for this topic. You will also learn tracing, common mistakes, nested series, and how to think mathematically while writing Java programs.

while loop

Repeats while a condition stays true

Nested while

A while loop inside another while loop

Series

Add terms one by one using loops

Tracing

Follow each step carefully to avoid mistakes

What is a while loop?

A while loop repeats a block of code as long as a condition remains true.

while (condition) {
    // code to repeat
}

First Java checks the condition. If it is true, the body runs. Then Java checks the condition again. This continues until the condition becomes false.

Simple example

int i = 1;

while (i <= 5) {
    System.out.println(i);
    i++;
}

This prints the numbers from 1 to 5.

When should you use while instead of for?

A for loop is often best when you clearly know the counting pattern. A while loop is often best when the repetition depends mainly on a condition.

But mathematically, both can often solve the same problem. In this lesson we will deliberately use while a lot.

Basic structure of a while loop

int i = 1;          // initialization

while (i <= 5) {    // condition
    System.out.println(i);
    i++;            // update
}
Part Meaning
Initialization Set the starting value before the loop begins
Condition Controls whether the loop should continue
Update Changes the loop variable so the loop can move forward

If you forget the update, the loop may never end.

Tracing a while loop

int i = 1;

while (i <= 3) {
    System.out.println("i = " + i);
    i++;
}
  1. Start with i = 1.
  2. Check i <= 3. True. Print 1.
  3. Increase i to 2.
  4. Check again. True. Print 2.
  5. Increase i to 3.
  6. Check again. True. Print 3.
  7. Increase i to 4.
  8. Check again. False. Stop.

What is a series?

A series is a sum of terms. For example:

To calculate a series using Java, we usually:

  1. Start with a sum variable, usually 0.
  2. Generate each term using a loop.
  3. Add each term into the sum.

Summation of first n natural numbers

Let us calculate: 1 + 2 + 3 + ... + n

int n = 5;
int i = 1;
int sum = 0;

while (i <= n) {
    sum = sum + i;
    i++;
}

System.out.println("Sum = " + sum);

For n = 5, the result is 15.

Trace table idea

i = 1, sum = 1
i = 2, sum = 3
i = 3, sum = 6
i = 4, sum = 10
i = 5, sum = 15

Summation of even numbers

Example series: 2 + 4 + 6 + 8 + ...

int n = 10;
int i = 2;
int sum = 0;

while (i <= n) {
    sum += i;
    i += 2;
}

System.out.println("Sum of even numbers = " + sum);

If n = 10, this adds 2, 4, 6, 8, and 10.

Summation of odd numbers

int n = 9;
int i = 1;
int sum = 0;

while (i <= n) {
    sum += i;
    i += 2;
}

System.out.println("Sum of odd numbers = " + sum);

Summation of squares

Example series: 1² + 2² + 3² + ... + n²

int n = 5;
int i = 1;
int sum = 0;

while (i <= n) {
    sum += i * i;
    i++;
}

System.out.println("Sum of squares = " + sum);

For n = 5, this becomes 1 + 4 + 9 + 16 + 25 = 55.

Summation of cubes

int n = 4;
int i = 1;
int sum = 0;

while (i <= n) {
    sum += i * i * i;
    i++;
}

System.out.println("Sum of cubes = " + sum);

Summation of a general arithmetic-type series

Suppose the series is: 3 + 6 + 9 + 12 + ... + n

int n = 18;
int term = 3;
int sum = 0;

while (term <= n) {
    sum += term;
    term += 3;
}

System.out.println("Sum = " + sum);

This works because each term is increasing by 3.

Summation of fractional series using double

Consider the series: 1 + 1/2 + 1/3 + 1/4 + ... + 1/n

int n = 5;
int i = 1;
double sum = 0.0;

while (i <= n) {
    sum += 1.0 / i;
    i++;
}

System.out.println("Sum = " + sum);

We use 1.0 / i instead of 1 / i, because integer division would give wrong results for most terms.

Alternating series

Some series alternate between positive and negative terms, for example: 1 - 2 + 3 - 4 + 5 - 6 + ...

int n = 6;
int i = 1;
int sum = 0;

while (i <= n) {
    if (i % 2 == 0) {
        sum -= i;
    } else {
        sum += i;
    }
    i++;
}

System.out.println("Sum = " + sum);

Series with factorial terms

Consider the series: 1! + 2! + 3! + ... + n!

int n = 5;
int i = 1;
int fact = 1;
int sum = 0;

while (i <= n) {
    fact = fact * i;
    sum = sum + fact;
    i++;
}

System.out.println("Sum of factorial series = " + sum);

Notice that we do not calculate each factorial from the beginning every time. We keep building the factorial step by step.

Series with powers

Suppose the series is: 2¹ + 2² + 2³ + ... + 2ⁿ

int n = 5;
int i = 1;
int sum = 0;

while (i <= n) {
    sum += (int)Math.pow(2, i);
    i++;
}

System.out.println("Sum = " + sum);

This uses the Math.pow() method.

Term-by-term thinking for series

The most important skill in summation problems is identifying the term. Once you know how one term is generated, the loop becomes easy.

Series Term idea
1 + 2 + 3 + ... + n term = i
2 + 4 + 6 + ... term = i, increase by 2
1² + 2² + 3² + ... term = i * i
1³ + 2³ + 3³ + ... term = i * i * i
1 + 1/2 + 1/3 + ... term = 1.0 / i
1! + 2! + 3! + ... term = running factorial

What is a nested while loop?

A nested while loop means one while loop is written inside another while loop. The inner loop runs fully for each iteration of the outer loop.

int i = 1;

while (i <= 3) {
    int j = 1;

    while (j <= 2) {
        System.out.println("i = " + i + ", j = " + j);
        j++;
    }

    i++;
}

The inner loop variable must usually be initialized inside the outer loop, otherwise it may not reset properly.

Nested while loops for rectangular patterns

int row = 1;

while (row <= 3) {
    int col = 1;

    while (col <= 5) {
        System.out.print("* ");
        col++;
    }

    System.out.println();
    row++;
}

Nested while loops for triangular patterns

int row = 1;

while (row <= 5) {
    int col = 1;

    while (col <= row) {
        System.out.print(col + " ");
        col++;
    }

    System.out.println();
    row++;
}

Nested while loops and summation of double series

Now we come to the main focus: using nested while loops for more advanced summation.

Example 1: Sum of a multiplication table grid

Compute: 1×1 + 1×2 + 1×3 + 2×1 + 2×2 + 2×3

int i = 1;
int sum = 0;

while (i <= 2) {
    int j = 1;

    while (j <= 3) {
        sum += i * j;
        j++;
    }

    i++;
}

System.out.println("Sum = " + sum);

Example 2: Summation row by row

Suppose we want: (1) + (1+2) + (1+2+3) + ... + (1+2+...+n)

int n = 4;
int i = 1;
int totalSum = 0;

while (i <= n) {
    int j = 1;
    int rowSum = 0;

    while (j <= i) {
        rowSum += j;
        j++;
    }

    totalSum += rowSum;
    i++;
}

System.out.println("Total sum = " + totalSum);

For n = 4, this becomes: 1 + (1+2) + (1+2+3) + (1+2+3+4).

Example 3: Nested summation of squares

Consider: (1²) + (1²+2²) + (1²+2²+3²) + ...

int n = 3;
int i = 1;
int totalSum = 0;

while (i <= n) {
    int j = 1;
    int rowSum = 0;

    while (j <= i) {
        rowSum += j * j;
        j++;
    }

    totalSum += rowSum;
    i++;
}

System.out.println("Total sum = " + totalSum);

Example 4: Harmonic-style nested series

Consider: (1) + (1 + 1/2) + (1 + 1/2 + 1/3) + ...

int n = 4;
int i = 1;
double totalSum = 0.0;

while (i <= n) {
    int j = 1;
    double rowSum = 0.0;

    while (j <= i) {
        rowSum += 1.0 / j;
        j++;
    }

    totalSum += rowSum;
    i++;
}

System.out.println("Total sum = " + totalSum);

Example 5: Factorial inside nested summation

Consider: (1!) + (1!+2!) + (1!+2!+3!) + ...

int n = 4;
int i = 1;
int totalSum = 0;

while (i <= n) {
    int j = 1;
    int fact = 1;
    int rowSum = 0;

    while (j <= i) {
        fact *= j;
        rowSum += fact;
        j++;
    }

    totalSum += rowSum;
    i++;
}

System.out.println("Total sum = " + totalSum);

Important tracing idea for nested series

In nested summation problems, always ask:

  1. What does the outer loop represent?
  2. What does the inner loop represent?
  3. What is one term?
  4. What is one row sum?
  5. How do all row sums combine into the total sum?

This way of thinking makes complicated summation programs much easier.

Common mistakes in while loop series programs

Infinite while loop warning

int i = 1;

while (i <= 5) {
    System.out.println(i);
}

This loop never changes i, so the condition stays true forever. Always check that your loop variable is moving toward the stopping condition.

Complete example

public class Main {
    public static void main(String[] args) {
        // 1. Simple while loop
        int i = 1;
        int sum1 = 0;
        while (i <= 5) {
            sum1 += i;
            i++;
        }
        System.out.println("Sum 1 to 5 = " + sum1);

        // 2. Sum of squares
        i = 1;
        int sumSquares = 0;
        while (i <= 4) {
            sumSquares += i * i;
            i++;
        }
        System.out.println("Sum of squares = " + sumSquares);

        // 3. Fraction series
        i = 1;
        double harmonic = 0.0;
        while (i <= 4) {
            harmonic += 1.0 / i;
            i++;
        }
        System.out.println("Harmonic-like sum = " + harmonic);

        // 4. Nested while row sums
        int row = 1;
        int total = 0;
        while (row <= 4) {
            int col = 1;
            int rowSum = 0;

            while (col <= row) {
                rowSum += col;
                col++;
            }

            total += rowSum;
            row++;
        }
        System.out.println("Nested row total = " + total);
    }
}

Assignments

Assignment 1: Use a while loop to print numbers from 1 to 20.
Assignment 2: Use a while loop to find the sum of natural numbers from 1 to n.
Assignment 3: Find the sum of even numbers up to n using a while loop.
Assignment 4: Find the sum of odd numbers up to n using a while loop.
Assignment 5: Find the sum of squares from 1² to n².
Assignment 6: Find the sum of cubes from 1³ to n³.
Assignment 7: Compute 1 + 1/2 + 1/3 + ... + 1/n correctly using double.
Assignment 8: Compute the series 1! + 2! + 3! + ... + n!.
Assignment 9: Use nested while loops to compute (1) + (1+2) + (1+2+3) + ... + (1+2+...+n).
Assignment 10: Use nested while loops to compute (1²) + (1²+2²) + (1²+2²+3²) + ....
Assignment 11: Use nested while loops to print a rectangle and a right triangle.
Assignment 12: Design your own series and write a while-loop program for it.

Interactive MCQ Quiz

Choose one answer for each question and click Check Answers.

Total Questions: 0

0 / 0

Your result will appear here.

Quick revision