๐ WAYPOINT LESSON
Nested loops
โญ beginnerโณ 12 min read๐ Lesson 19 of 256
Iteration products, dependent inner bounds, total-cost intuition.
Nested loops โ the inner loop runs completely for every single pass of the outer loop:
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
System.out.print(col);
}
System.out.println();
}
// 1234
// 1234
// 1234
The inner body ran 3 ร 4 = 12 times. When you see nested loops, compute the total iteration count first: it is the product.
Triangle patterns show the inner bound depending on the outer variable:
for (int row = 1; row <= 4; row++) {
for (int star = 1; star <= row; star++) {
System.out.print("*");
}
System.out.println();
}
prints a staircase: 1, 2, 3, then 4 stars. Total work: 1+2+3+4 = 10 iterations โ the shape of many O(nยฒ) discussions later.
do-while (rare on the exam, know its shape): the body runs first, the test runs after โ so the body always executes at least once. Use while/for in your own code; trace do-when it appears.