Four classic patterns
A loop inside another loop runs its whole inner loop once for every iteration of the outer one. That's how you walk grids, compare every pair, and print patterns, and it's why the work grows as rows × columns (often n²).
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Print an inverted right triangle of height 4 using #.
Print the numbers 1 to 3 in a 3 × 3 grid where each row repeats its row number (1 1 1, 2 2 2, 3 3 3).
Given int[] a = {2, 7, 4, 7, 2, 9}, use nested loops to print every pair of positions that hold equal values.
Explain it without notes
If the outer loop runs 5 times and the inner loop runs 4 times, how many times does the inner body run, and why?
How do you approach printing a pattern such as a pyramid?
Why does the inner loop in for (int j = i + 1; j < n; j++) produce each pair once, and how many iterations does it do?
Why should the inner counter be declared in the inner loop's header?
Expected output
Right triangle:
*
**
***
****
Pyramid:
*
***
*****
*******
Floyd's triangle:
1
2 3
4 5 6
7 8 9 10
Hollow square:
####
#..#
#..#
####