A loop can contain another loop. For every single pass of the outer loop, the inner loop runs all the way through. Nested loops are how you build grids, tables, and rows of repeated output.
for (int r = 1; r <= 2; r++) { for (int c = 1; c <= 3; c++) { System.out.print("*"); } System.out.println(); }
The inner loop prints ***; the outer loop repeats that on 2 rows. Output is two lines of *** (6 stars total).
***
▶ Try it: run this, then change 2 (rows) and 3 (columns) and re-run — you get a rectangle of any size.
2
3
How many times does print("*") run in total?
print("*")
for (int r = 1; r <= 2; r++) { for (int c = 1; c <= 3; c++) { System.out.print("*"); } }
For each single pass of the outer loop, how many times does the inner loop run?
Type exactly what this prints:
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { System.out.print("x"); } System.out.println(); }
True or false?