2.11 - Nested Iteration
Nested iteration is a loop inside another loop. The inner loop has to completely finish all of its iterations before the outer loop can move on to its next one.
for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { System.out.println("i=" + i + ", j=" + j); } } // outputs: // i=0, j=0 // i=0, j=1 // i=1, j=0 // i=1, j=1 // i=2, j=0 // i=2, j=1
For each single pass of the outer loop, the inner loop runs from start to finish. Here the outer loop runs 3 times and the inner loop runs 2 times per outer pass, so the print statement runs times (see 2.12).
The inner loop’s bounds can use the outer loop’s variable. This is how you print triangle patterns:
for (int row = 1; row <= 4; row++) { for (int col = 1; col <= row; col++) { System.out.print("*"); } System.out.println(); // end the row after the inner loop finishes } // output: // * // ** // *** // ****
Nested loops work with strings too. This prints every substring of
"abc":String s = "abc"; for (int start = 0; start < s.length(); start++) { for (int end = start + 1; end <= s.length(); end++) { System.out.println(s.substring(start, end)); } } // prints a, ab, abc, b, bc, c (one per line)
A common bug: if the inner loop’s variable is declared before the outer loop, it never gets reset, so the inner loop only runs during the first outer pass. Declare (or reset) it inside the outer loop instead.
int j = 0; for (int i = 0; i < 3; i++) { while (j < 2) { System.out.println(i + " " + j); j++; } } // prints only 0 0 and 0 1, because j stays at 2 after the first pass // fix: move int j = 0; inside the for loop, right before the while