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.
Repeats while a condition stays true
A while loop inside another while loop
Add terms one by one using loops
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.
- Use
forwhen you know the start, end, and update clearly. - Use
whilewhen the condition is the main idea.
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++;
}
- Start with
i = 1. - Check
i <= 3. True. Print 1. - Increase
ito 2. - Check again. True. Print 2.
- Increase
ito 3. - Check again. True. Print 3.
- Increase
ito 4. - Check again. False. Stop.
What is a series?
A series is a sum of terms. For example:
1 + 2 + 3 + 4 + 52 + 4 + 6 + 8 + 101² + 2² + 3² + 4²1 + 1/2 + 1/3 + 1/4
To calculate a series using Java, we usually:
- Start with a sum variable, usually 0.
- Generate each term using a loop.
- 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:
- What does the outer loop represent?
- What does the inner loop represent?
- What is one term?
- What is one row sum?
- 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
- Forgetting to update the loop variable, causing an infinite loop.
- Using
intinstead ofdoublefor fractional series. - Writing
1 / iinstead of1.0 / i. - Forgetting to reset inner variables in nested loops.
- Adding the wrong thing to the sum, such as adding
iwhen the term should bei*i.
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
1 + 1/2 + 1/3 + ... + 1/n correctly using double.
1! + 2! + 3! + ... + n!.
(1) + (1+2) + (1+2+3) + ... + (1+2+...+n).
(1²) + (1²+2²) + (1²+2²+3²) + ....
Interactive MCQ Quiz
Choose one answer for each question and click Check Answers.
0 / 0
Your result will appear here.
Quick revision
- A while loop repeats while a condition is true.
- Always initialize before the loop and update inside the loop.
- Series programs usually use a running sum variable.
- For fractional series, use
doubleand1.0 / i. - A nested while loop has one while loop inside another.
- In nested loops, inner variables often need resetting inside the outer loop.
- For complex summations, think in terms of term, row sum, and total sum.