Nested Iteration
Loops inside loops: the order in which their bodies run, inner bounds that depend on the outer variable, counting how many times the inner body executes, and using nested loops to build patterns and examine every pair.
Nested iteration statements are iteration statements that appear in the body of another iteration statement. When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration. Nested loops handle two-dimensional work: rows and columns of a table, lines of a pattern, or every pair of values from a range. The key skills are following the order of execution and counting how many times the innermost statements run.
1Loops Inside Loops
A loop body can contain any statements, including another loop. The loop that contains the other is the outer loop; the one inside is the inner loop. Each time the outer loop's body runs, the inner loop runs from start to finish. Nested loops are the natural tool whenever a task has two dimensions, such as rows and columns, or whenever every combination of two values must be considered.
Each loop needs its own control variable, conventionally i for the outer loop and j for the inner one, or descriptive names such as row and col. The inner loop can use the outer variable, but the outer loop should not depend on anything the inner loop leaves behind except through clearly named variables.
| Question | How to answer it |
|---|---|
| Which loop finishes first? | The inner loop completes all its iterations before the outer loop continues |
| How many times does the inner body run (fixed bound)? | Outer passes × inner passes |
| How many times (bound depends on outer variable)? | Add the inner pass counts for each outer value |
| Does the inner loop restart? | Yes, from its initialization, on every outer pass |
A Multiplication Table
Print a table with 3 rows and 4 columns, where each entry is row × column.
for (int i = 1; i <= 3; i++)
{
String row = "" + i;
for (int j = 2; j <= 4; j++)
{
row = row + " " + (i * j);
}
System.out.println(row);
}
1 2 3 4
2 4 6 8
3 6 9 12
- 1Outer loop: one row per pass. It starts a fresh
rowstring with the first entry,i × 1. - 2Inner loop: the rest of the row. For
jfrom 2 to 4 it appendsi × j. - 3Only after the inner loop finishes is the row printed and the outer loop moves on.
If the inner loop reuses the outer loop's variable, each changes the other and the loops behave unpredictably; with for loops that declare int i twice, the code does not compile. Give each loop its own control variable.
2Order of Execution
When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration. With an outer loop over i = 1 to 3 and an inner loop over j = 1 to 4, the inner body runs for j = 1, 2, 3, 4 with i = 1, then all four again with i = 2, then with i = 3: twelve runs in total, row by row.
An odometer is a good picture: the right-hand digit (the inner loop) cycles through all its values before the next digit to the left (the outer loop) advances by one. Statements in the outer body that come after the inner loop run once per outer pass, after the inner loop has finished; statements before it run once per outer pass before the inner loop starts.
| Outer i | Inner j values | Inner passes | Output for this i |
|---|---|---|---|
| 1 | 1, 2, 3 | 3 | i=1 j=1 / j=2 / j=3, end of i=1 |
| 2 | 1, 2, 3 | 3 | i=2 j=1 / j=2 / j=3, end of i=2 |
Watching Both Variables
Predict the exact order of the output.
for (int i = 1; i <= 2; i++)
{
for (int j = 1; j <= 3; j++)
{
System.out.println("i=" + i + " j=" + j);
}
System.out.println("end of i=" + i);
}
i=1 j=1
i=1 j=2
i=1 j=3
end of i=1
i=2 j=1
i=2 j=2
i=2 j=3
end of i=2
- 1
i= 1. The inner loop runs all three values ofjbefore anything else happens. - 2After the inner loop the outer body continues with its own statement: "end of i=1".
- 3
i= 2. The inner loop starts over atj= 1, because its initialization runs again.
3Inner Bounds That Depend on the Outer Variable
The inner loop's header may use the outer loop variable. In a triangle pattern, row r has r stars, so the inner loop runs while j <= r: once on the first row, twice on the second, and so on. The inner loop can also start at the outer value, as in for (int b = a; ...), which is how nested loops avoid examining the same pair twice.
Variables that must start fresh for each outer pass, such as a string being built for one row, are initialized inside the outer loop but before the inner loop. Variables that accumulate across the whole nested process, such as a total count, are initialized before the outer loop.
A Triangle of Stars
Print 4 rows where row r has r stars.
for (int r = 1; r <= 4; r++)
{
String line = "";
for (int j = 1; j <= r; j++)
{
line = line + "*";
}
System.out.println(line);
}
*
**
***
****
- 1The inner bound is
r, the outer variable, so the inner loop runs once on the first row, twice on the second, and so on. - 2
lineis reset at the start of each outer pass, so each row starts empty.
If the string for one row is created before the outer loop, rows pile onto each other; if it is created inside the inner loop, each row holds only one character. Create per-row variables inside the outer loop, before the inner loop begins.
4Counting Inner-Body Executions
How many times a statement in the inner body runs is a frequent question, and a preview of analyzing how much work a program does. When the inner loop's count does not depend on the outer variable, multiply: 5 outer passes with 3 inner passes each gives 15 runs. When it does depend on the outer variable, add the inner counts for each outer pass: inner counts of 0, 1, 2, 3, 4 add to 10.
For the common pattern where the inner loop runs i times for i = 1 to n, the total is 1 + 2 + … + n = n(n + 1) / 2. Listing the inner count for the first few and last outer values, then adding, is a reliable method even when no formula comes to mind.
| Inner loop header | Outer i from 0 to 4 | Total inner passes |
|---|---|---|
for (int j = 0; j < 3; j++) | 3 each time | 15 |
for (int j = 0; j < i; j++) | 0, 1, 2, 3, 4 | 10 |
for (int j = 0; j <= i; j++) | 1, 2, 3, 4, 5 | 15 |
for (int j = i; j < 5; j++) | 5, 4, 3, 2, 1 | 15 |
How Many Times Does the Inner Body Run?
Predict both counts.
int a = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
a++;
}
}
int b = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < i; j++)
{
b++;
}
}
System.out.println(a + " " + b);
15 10
- 1Fixed bound. 5 outer passes × 3 inner passes = 15.
- 2Dependent bound. For
i= 0, 1, 2, 3, 4 the inner loop runs 0, 1, 2, 3, 4 times: 10 in total.
5Examining Every Pair
Nested loops can check every combination of two values: the outer loop chooses the first, the inner loop chooses the second, and an if inside tests the pair. If order matters, both loops run over the full range; if it does not, starting the inner loop at the outer value (or one past it) checks each unordered pair once and skips duplicates.
The same idea applies to strings: an outer loop over each position and an inner loop over every later position compare every pair of characters. This is how a program can count repeated letters or find whether any two positions hold the same character.
Finding All Pairs With a Given Sum
List every pair of whole numbers a ≤ b, each from 1 to 9, whose sum is 10.
int pairs = 0;
for (int a = 1; a <= 9; a++)
{
for (int b = a; b <= 9; b++)
{
if (a + b == 10)
{
System.out.println(a + " + " + b);
pairs++;
}
}
}
System.out.println(pairs + " pairs");
1 + 9
2 + 8
3 + 7
4 + 6
5 + 5
5 pairs
- 1Every pair once. Starting the inner loop at
aavoids listing both 1 + 9 and 9 + 1. - 2Selection inside. Only pairs that meet the criterion print and are counted.
Counting Matching Letter Pairs
Count the pairs of positions i < j in "banana" that hold the same letter.
String word = "banana";
int matches = 0;
for (int i = 0; i < word.length(); i++)
{
for (int j = i + 1; j < word.length(); j++)
{
if (word.substring(i, i + 1).equals(word.substring(j, j + 1)))
{
matches++;
}
}
}
System.out.println(matches);
4
- 1Pairs with i < j. The inner loop starts at
i + 1, so each pair of positions is compared once. - 2The a's at 1, 3, 5 form 3 pairs; the n's at 2, 4 form 1 pair; "b" has no partner.
If both loops run over the full range, the pair (1, 9) is found once as a = 1, b = 9 and again as a = 9, b = 1, and a value can even be paired with itself. When order does not matter, start the inner loop at a (or a + 1 to exclude self-pairs).
6Resetting the Inner Loop
A for loop's initialization runs every time the loop statement is reached, so an inner for loop automatically restarts on each outer pass. An inner while loop does not have that built in: if its counter is declared and set before the outer loop, it keeps its final value after the first outer pass, and the inner loop runs zero times on every later pass.
Whenever an inner while loop is used, set its counter inside the outer loop, immediately before the inner loop. Tracing the second outer pass is the quickest way to catch this mistake, because the first pass always looks correct.
Forgetting to Reset the Inner Loop
The inner while loop's counter is declared outside the outer loop. Predict the output.
int j = 1;
for (int i = 1; i <= 3; i++)
{
while (j <= 2)
{
System.out.println(i + "," + j);
j++;
}
}
1,1
1,2
- 1First outer pass. The inner loop prints 1,1 and 1,2, leaving
jat 3. - 2Later passes.
jis still 3, soj <= 2isfalseimmediately and the inner loop runs zero times. - 3Fix. Set
j = 1;at the start of each outer pass, or use aforloop, whose initialization runs every time it is reached.
for loop's header guarantees this, while a while loop needs an explicit reset.Nested loop bugs often appear only on the second or later outer pass: a counter that was not reset, an accumulator that was not cleared, or a bound that depends on the wrong variable. Always trace at least two outer passes.
Four Habits for Nested Loops
1. Inner Finishes First
All inner passes run before the outer variable changes.
2. Multiply or Add
Fixed inner bound: multiply. Dependent bound: add.
3. Place Each Variable Carefully
Totals before the outer loop; per-row values inside it.
4. Trace Two Outer Passes
Resets and bounds fail on the second pass.
Nested iteration statements are iteration statements that appear in the body of another iteration statement. When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration. The number of times the inner body runs is the product of the pass counts when the inner bound is fixed, or the sum of the inner counts when the inner bound depends on the outer loop variable.