Sub topic 3
Place loops inside loops
A nested loop is a loop placed inside another loop. The outer loop repeats the inner loop from the start each time. One pass through a loop is called an iteration.
Nested loops are useful for working with rows and columns. In this example, the outer loop chooses a row. The inner loop chooses a column.
Save this program as Main.java. Compile it with javac Main.java, then run it with java Main.
public class Main {
public static void main(String[] args) {
for (int row = 0; row < 2; row++) {
for (int column = 0; column < 4; column++) {
if (column == 1) {
continue;
}
if (column == 3) {
break;
}
System.out.println(row + "," + column);
}
}
}
}The program prints 0,0 and 0,2 on separate lines. Then it prints 1,0 and 1,2 on separate lines. Each line shows a row and column.
Exit or skip an iteration
The continue statement skips the rest of the current iteration. Here, it skips printing when column is 1. The inner loop then increases column and tests its condition again.
The break statement exits the nearest loop. Here, it exits the inner loop when column is 3. The outer loop then moves to its next iteration, if there is one.
Trace the loops
To trace a loop is to follow its values and actions one step at a time. For each row, the inner loop starts column at 0:
| Column | Action |
|---|---|
| 0 | Print the row and column |
| 1 | Skip the print with continue |
| 2 | Print the row and column |
| 3 | Exit the inner loop with break |
A condition is a test that is either true or false. The outer condition, row < 2, allows rows 0 and 1. A boundary is the point where a condition changes its result. Changing the test to row <= 2 would also allow row 2, which may be one row too many.
Check that loop variables move toward a stopping point. If row never increases, its condition stays true. That creates an infinite loop: a loop that never ends on its own.
Exercise
What extra lines appear if you remove the break statement and its if block?
Show answer
The program also prints 0,3 after 0,2 and 1,3 after 1,2.
Exercise
What happens if you remove row++ from the outer loop header?
Show answer
Row stays at 0, so the outer loop keeps repeating and prints 0,0 and 0,2 over and over.