Control Flow & Loops

Nested Loops & Patterns

15 min Lesson 9 of 14

Nested Loops & Patterns

A nested loop is simply a loop placed inside the body of another loop. Every time the outer loop completes one iteration, the inner loop runs to completion. This mechanism is the foundation of anything that involves a grid, a table, or a repeated pattern built from rows and columns.

How Nesting Works — The Mental Model

Think of a clock: the minute hand (inner loop) completes a full revolution every time the hour hand (outer loop) moves one step. Concretely, if the outer loop runs 3 times and the inner loop runs 4 times, the inner body executes 3 × 4 = 12 times total.

for (int outer = 1; outer <= 3; outer++) { for (int inner = 1; inner <= 4; inner++) { System.out.print("(" + outer + "," + inner + ") "); } System.out.println(); // move to next line after each outer iteration }

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)
Key rule: each loop needs its own control variable. Reusing the same variable name in both loops will cause the outer loop to be affected by the inner loop — a common beginner mistake.

Printing a Rectangle of Stars

The simplest pattern is a filled rectangle. Two variables control it: rows and cols.

int rows = 4; int cols = 6; for (int r = 1; r <= rows; r++) { for (int c = 1; c <= cols; c++) { System.out.print("* "); } System.out.println(); }

Output:

* * * * * * * * * * * * * * * * * * * * * * * *

Right-Angled Triangle

The trick for a triangle is making the inner loop's upper bound depend on the outer loop variable. Row 1 prints 1 star, row 2 prints 2 stars, and so on.

int n = 5; for (int r = 1; r <= n; r++) { for (int c = 1; c <= r; c++) { // inner limit = r System.out.print("* "); } System.out.println(); }

Output:

* * * * * * * * * * * * * * *
Pattern insight: whenever the inner loop's bound is a function of the outer variable, you get a triangle or pyramid shape instead of a rectangle. Experiment by trying n - r + 1 as the inner bound to get an inverted triangle.

Multiplication Table

A classic and practical use of nested loops is printing a multiplication table. The outer loop controls the row (multiplier 1), the inner loop controls the column (multiplier 2).

for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { System.out.printf("%4d", i * j); // %4d = width-4 integer, keeps columns aligned } System.out.println(); }

Output:

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

System.out.printf formats the number into a fixed-width field so the columns line up neatly, regardless of how many digits the product has.

Traversing a 2-D Array

Two-dimensional arrays in Java are arrays of arrays. You declare them as int[][] grid and access an element with grid[row][col]. Nested loops are the natural way to visit every cell.

int[][] grid = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; for (int row = 0; row < grid.length; row++) { for (int col = 0; col < grid[row].length; col++) { System.out.printf("%3d", grid[row][col]); } System.out.println(); }

Output:

1 2 3 4 5 6 7 8 9

Using grid[row].length (not a hard-coded constant) makes the code safe for jagged arrays where rows may have different lengths.

Watch the index order! Java 2-D arrays are row-major: the first index is always the row and the second is the column. Swapping them — writing grid[col][row] — will cause an ArrayIndexOutOfBoundsException the moment rows and columns have different sizes.

Performance: Nested Loops Are O(n²)

If both loops run n times, the inner body executes n × n = n² times. For small n this is fine. For large data sets (thousands of rows), nested loops become slow quickly. This is why understanding when a nested loop is necessary — versus when a different data structure or algorithm avoids it — becomes important as you advance.

Summary

  • A nested loop places one loop inside another; the inner loop completes fully on every outer iteration.
  • Use separate control variables for each loop level.
  • Tying the inner bound to the outer variable produces triangle and pyramid patterns.
  • Nested loops are the standard tool for multiplication tables and 2-D array traversal.
  • Total iterations = outer count × inner count — keep this in mind for performance.