Nested Loops
A cinema hall has rows, and every row has seats. To check every seat, you walk row by row, and in each row you go seat by seat. That's two loops, one inside the other: a nested loop. The inner loop runs completely for every single round of the outer loop.
Rows and Seats
public class Seats {
public static void main(String[] args) {
for (char row = 'A'; row <= 'C'; row++) {
for (int seat = 1; seat <= 4; seat++) {
System.out.print(row + "" + seat + " ");
}
System.out.println();
}
}
}A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4How it works
- Line 3, the outer loop, picks a row: A, then B, then C.
- Line 4, the inner loop, runs seats 1 to 4 for that row, then finishes.
- Line 7 ends the line after each row. Then the outer loop moves to the next row, and the inner loop starts again from seat 1.
- Total: 3 rows × 4 seats = 12 rounds of the inner body.
row + "" + seat joins the two as text. Without the empty string, row + seat would add the char and the int as numbers.
Try it yourself: swap the two loops so seats are on the outside. How does the printed grid change?
A Multiplication Table
public class Table {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
}
} 1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25%4d gives every number 4 characters, so the columns line up (see "Format Specifiers").
When the Inner Loop Depends on the Outer
The inner loop's limit can use the outer variable. This prints a triangle, where row i has i stars:
public class Triangle {
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}*
**
***
****The lesson "Basic Java Programs" has more patterns like this.
Common Mistakes
Reusing the same counter name. Using i for both loops doesn't compile when the scopes overlap. Use i and j, or better, row and seat.
Putting println() inside the inner loop. Every value then lands on its own line instead of forming a row.
Expecting break to leave both loops. A plain break leaves only the innermost loop. The lesson "Labeled Break and Continue" shows how to leave both.
Practice
- Easy: Print a 4 × 6 rectangle of
#characters. - Harder: Print the multiplication table from 1 to 9, but only the half where
j <= i(a triangle of products).
Key Takeaways
Was this tutorial helpful?