Sub topic 7
Place Loops Inside Loops
A nested loop is a loop placed inside another loop. The outside loop is the outer loop. The loop inside it is the inner loop.
Nested loops are useful when you need to repeat a set of steps for each item in another set. For example, you can visit each column in each row of a grid.
This chapter assumes you have practiced basic for loops. An iteration is one pass through a loop’s body, the statements inside its braces.
Visit rows and columns
The following program prints pairs of row and column numbers. Save it in a file named Coordinates.java.
public class Coordinates {
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);
}
}
}
}Compile it with javac Coordinates.java, then run it with java Coordinates. The output is:
0,0
0,1
0,2
1,0
1,1
1,2The outer loop starts with row equal to 0. Before row changes, the inner loop runs through all its column values: 0, 1, and 2.
Then the outer loop changes row to 1. The inner loop starts again at column = 0 and runs through all three columns.
The inner loop finishes once for each outer iteration. Here, that means two sets of three lines, or six lines in total.
Trace the order
A trace is a step-by-step record of what a program does. This table groups the output by outer iteration:
| Outer iteration | Value of `row` | Values of `column` | Pairs printed |
|---|---|---|---|
| First | 0 | 0, 1, 2 | `0,0`, `0,1`, `0,2` |
| Second | 1 | 0, 1, 2 | `1,0`, `1,1`, `1,2` |
Notice that row stays the same while column changes. Once the inner loop finishes, the outer loop updates row. Then the inner loop starts over.
This diagram shows the same path. A condition is a test that is either true or false.
The column variable starts at 0 each time the outer loop enters the inner loop. It does not keep the value it had when the previous inner loop finished.
Know where loop variables work
Scope is the part of a program where a variable can be used. In the coordinates example, row is declared in the outer loop. The inner loop is inside that loop, so it can use row.
The column variable is declared in the inner loop. It can be used in the inner loop’s body, but not after the inner loop ends. Likewise, row cannot be used after the outer loop ends.
Change the inner loop for each row
The inner loop does not always need to run the same number of times. It can use the outer variable to decide when to stop.
Save this program as Triangle.java, compile it with javac Triangle.java, and run it with java Triangle.
public class Triangle {
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:
*
**
***
****For each row, the inner loop prints one star for each column number from 1 through the current value of row. When row is 3, for example, the inner loop prints three stars.
System.out.print keeps the next output on the same line. After the inner loop finishes, System.out.println() moves to a new line. It is outside the inner loop but inside the outer loop, so it runs once per row.
Check the boundaries
A boundary is a limit on the values a loop visits. Read each condition carefully when tracing nested loops.
- In the coordinates example,
row < 2visits rows0and1, not row2. - In the triangle example,
row <= 4includes row4. - In the triangle, the inner limit changes with
row. The four rows have1 + 2 + 3 + 4, or10, stars in total.
A good way to check a nested loop is to trace the first outer iteration completely. Then check that the inner loop starts again as expected on the next outer iteration. Also check the last value each condition allows.
Practice
Exercise
An outer loop visits rows 0 through 2. For each row, an inner loop visits columns 0 through 1 and prints the pair. How many pairs are printed, and what is the last pair?
Show answer
There are 3 × 2 = 6 pairs. The last pair is 2,1.
Exercise
In the triangle program, how many stars print when row is 2? Why?
Show answer
Two stars print. The inner loop visits column values 1 and 2.
Exercise
In the coordinates program, can you use column after the inner loop ends but still inside the outer loop?
Show answer
No. column is declared in the inner loop, so it is outside its scope after that loop ends.