Sub topic 7
Place loops inside loops
A nested loop is a loop placed inside another loop. The outer loop repeats the larger task. The inner loop repeats a smaller task each time the outer loop runs.
Nested loops are useful when a task has groups with items inside them. For example, a grid has rows, and each row has columns. The outer loop can visit each row. The inner loop can visit each column in that row.
An iteration is one pass through a loop’s body. The body is the set of statements the loop repeats. In a nested loop, the inner loop can have several iterations during one outer-loop iteration.
Visit every position in a grid
Imagine a grid with two rows and three columns. Give the rows numbers 0 and 1. Give the columns numbers 0, 1, and 2.
This program prints every row and column pair:
public class Main {
public static void main(String[] args) {
for (int row = 0; row < 2; row++) {
for (int column = 0; column < 3; column++) {
System.out.println(row + "," + column);
}
}
}
}Save the program in a file named Main.java. Compile and run it:
javac Main.java
java MainThe output is:
0,0
0,1
0,2
1,0
1,1
1,2The outer loop uses row. It starts at 0 and runs while row < 2.
The inner loop uses column. It starts at 0 and runs while column < 3. The inner loop is inside the outer loop’s braces, so Java reaches it once for each value of row.
Trace the order
A trace is a step-by-step record of what a program does. The table shows the values each time the print statement runs.
| Print number | `row` | `column` | Output |
|---|---|---|---|
| 1 | 0 | 0 | `0,0` |
| 2 | 0 | 1 | `0,1` |
| 3 | 0 | 2 | `0,2` |
| 4 | 1 | 0 | `1,0` |
| 5 | 1 | 1 | `1,1` |
| 6 | 1 | 2 | `1,2` |
Notice that row stays at 0 while column changes from 0 to 2. Only after the inner loop finishes does row change to 1. Then the inner loop starts again at column 0.
Here is the same process as a diagram:
Look closely at the first row:
- The outer loop starts with
rowequal to 0. - The inner loop starts with
columnequal to 0. - The program prints
0,0,0,1, and0,2. - After
columnincreases to 3, the inner loop’s condition is false. The inner loop ends. - The outer loop increases
rowto 1.
The same inner-loop process then runs for row 1. After that, row becomes 2, so the outer loop’s condition is false and the program finishes.
Why does the column start over?
The inner loop’s header is reached again on each outer-loop iteration. Its initialization sets column to 0 each time.
If the inner loop did not start over, there would be no columns left to visit after the first row. Starting the inner loop again lets the program visit all three columns in each row.
Exercise
In the grid program, what pair is printed immediately after 0,2?
Show answer
1,0. The inner loop finishes for row 0. The outer loop moves to row 1, and the inner loop starts again at column 0.
Keep track of loop variables
The example uses two variables: row and column. A variable is a named place to store a value.
Each variable has a scope. Scope is the part of a program where a variable can be used. A variable declared in a for header is available in that loop’s header and body.
In the grid program:
rowis available in the outer loop’s header and body. That includes the inner loop.columnis available in the inner loop’s header and body.columnis not available after the inner loop ends, even within the rest of the outer loop’s body.- Neither variable is available after the outer loop ends.
Use a different name for each loop variable when their scopes overlap. Java does not let you declare a second local variable with the same name inside the first one’s scope.
Also check that each loop updates the right variable. If the inner loop is meant to advance column but changes row instead, it may not finish as expected.
Print a multiplication table
Nested loops can also build output a row at a time. This program prints a small multiplication table:
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 4; column++) {
System.out.print(row * column + " ");
}
System.out.println();
}
}
}The output is:
1 2 3 4
2 4 6 8
3 6 9 12The outer loop visits rows 1 through 3. For each row, the inner loop visits columns 1 through 4. The expression row * column finds the number to print at that position.
System.out.print prints without starting a new line. That keeps the values for one row together. After the inner loop finishes, System.out.println() starts a new line. It is inside the outer loop but outside the inner loop, so it runs once per row.
If the empty println() were inside the inner loop, the program would start a new line after every value instead. The placement of a statement matters: it decides which loop repeats that statement.
The table has three rows and four values per row. The multiplication statement runs 3 times 4, or 12 times. The empty println() runs only 3 times.
Count the inner iterations
In the multiplication table, every row has four columns. For this kind of nested loop, you can multiply:
- Count the outer iterations.
- Count the inner iterations for one outer iteration.
- Multiply the two counts.
For example, two rows with three columns each give 2 times 3, or 6, inner iterations.
This rule works when the inner loop runs the same number of times for every outer iteration. But an inner loop can also depend on the outer variable. In that case, its count may change.
Make a triangle
This program prints one more star on each line:
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 4; row++) {
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
}
}
}The output is:
*
**
***
****The inner condition is column <= row. The value of row sets how many stars appear on the current line.
| `row` | Values of `column` | Stars printed |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1, 2 | 2 |
| 3 | 1, 2, 3 | 3 |
| 4 | 1, 2, 3, 4 | 4 |
There are 1 + 2 + 3 + 4, or 10, inner iterations in total. Multiplying 4 rows by 4 stars would give 16, which is wrong. The inner loop does not print four stars on every row.
Exercise
If the triangle program runs the outer loop through row 5, how many stars appear on the last line, and how many appear in total?
Show answer
The last line has 5 stars. There are 15 stars in total: 1 + 2 + 3 + 4 + 5.
An inner loop can run zero times
A loop that tests its condition before its body may have no iterations. In a nested loop, that means the outer body can run even when the inner body does not.
For example, suppose an inner loop starts column at 0 and tests column < 0. The condition is false at once, so nothing in that inner body runs. Statements after the inner loop, but still inside the outer loop, can still run.
This matters when different groups have different sizes. A row with no items should not cause the program to visit an item that is not there.
Visit values in rows of an array
An array is a group of values stored together. A two-dimensional array is an array whose elements are themselves arrays. You can think of its inner arrays as rows.
The rows do not have to be the same length. The following program adds the values in each row, then adds all the rows together:
public class Main {
public static void main(String[] args) {
int[][] scores = {{3, 5, 2}, {4, 6}, {}};
int total = 0;
for (int row = 0; row < scores.length; row++) {
int rowTotal = 0;
for (int column = 0; column < scores[row].length; column++) {
rowTotal += scores[row][column];
}
System.out.println("Row " + row + ": " + rowTotal);
total += rowTotal;
}
System.out.println("Total: " + total);
}
}The output is:
Row 0: 10
Row 1: 10
Row 2: 0
Total: 20The outer array, scores, contains three rows. scores.length is the number of rows, so the outer loop visits row numbers 0, 1, and 2.
For each row, scores[row].length gives the number of values in that row. The inner loop uses that length to visit each value. scores[row][column] selects a value by its row and column numbers. An index is a number used to select an array element; Java array indexes start at 0.
The first row has three values. The second has two. The third is empty, so its length is 0 and the inner loop runs zero times for that row. The outer loop still prints Row 2: 0.
The position of each total matters:
rowTotalstarts at 0 inside the outer body. It starts fresh for every row.- The inner loop adds each value in the current row to
rowTotal. totalstarts at 0 before the outer loop. It keeps its value across all rows.- After each inner loop finishes, the program adds that row’s total to
total.
The program assumes every row is an array, even if it is empty. It also uses the current row’s length for the inner condition. Using scores.length there would use the number of rows instead of the number of values in the current row. That could miss values or try to reach past the end of a row.
Check boundaries and repetition
A boundary is a limit that decides where a loop starts or stops. A small boundary mistake can change every row of a nested loop.
Consider a row with three values. Its valid column indexes are 0, 1, and 2. Starting at 0 and testing column < 3 visits all three. Testing column <= 3 also tries column 3, which is past the end of the row.
An off-by-one error is a mistake where a loop runs one time too many or one time too few. In an array, trying to use an index past the end causes an error and stops the program unless the error is handled.
Use this checklist when a nested loop gives an unexpected result:
- Find the outer body and the inner body. Check which statements are inside each one.
- Write down the first value and the last value each loop should use.
- Trace the first two outer iterations. Check that the inner loop starts where you expect each time.
- Check that each loop updates its own variable and can eventually finish.
- Count the work. If every row is the same size, multiply the counts. If row sizes differ, add the inner counts.
- For arrays, check the length of the current row, not just the number of rows.
A nested loop can also do more work than it first appears to. If an outer loop runs 100 times and an inner loop runs 100 times for each outer iteration, the inner body runs 10,000 times. Counting iterations can help you spot work that grows quickly.
Exercise
An outer loop visits row numbers 0 through 2. For each row, an inner loop visits column numbers 0 through 3. How many pairs are visited, and what pair comes immediately after 1,3?
Show answer
The loops visit 12 pairs: 3 rows times 4 columns. The next pair is 2,0, because the inner loop starts again when the outer loop moves to row 2.