AI Hints
Home›Java Tutorial›break and continue, Nested Loops and Loop Patterns
Java · Lesson 41 of 120

Nested Loops

Loops inside loops.

⏱ 2 min read▶ Video at 52:05🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

You can put a loop inside another loop. For each lap of the outer loop, the inner loop runs all of its laps.

  • A loop inside a loop
  • Outer: once
  • Inner: all its laps

Rows and columns

The outer loop counts rows, one to three. For each row, the inner loop counts columns, one to four. After the inner loop, println ends the row. Run it. Three rows, with four pairs in each. Twelve in total.

Main.javajava
public class Main {
    public static void main(String[] args) {
        for (int row = 1; row <= 3; row++) {
            for (int col = 1; col <= 4; col++) {
                System.out.print("(" + row + "," + col + ") ");
            }
            System.out.println();
        }
    }
}
Output
(1,1) (1,2) (1,3) (1,4)
(2,1) (2,2) (2,3) (2,4)
(3,1) (3,2) (3,3) (3,4)

A triangle

Here, the inner loop runs up to row. So row one has one star, row two has two, and so on. Run it. A triangle of stars.

Main.javajava
public class Main {
    public static void main(String[] args) {
        for (int row = 1; row <= 5; row++) {
            for (int star = 1; star <= row; star++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}
Output
*
* *
* * *
* * * *
* * * * *

Nested loop tips

Use different names for each counter, like row and col, or i and j. The total work is outer laps times inner laps. And break only leaves the innermost loop.

keyvalue
Namesrow and col, or i and j
Workouter × inner laps
breakleaves the inner loop only
Use forgrids, tables, pairs

Summary

In nested loops, the inner loop runs completely, for every lap of the outer loop. Great for grids, and patterns. Next, common loop patterns.

Key takeaways
  • Loop in a loop
  • Inner runs fully
  • Grids and patterns
Next up: Loop Patterns — find, count, check