College Board Unit 2
How it works
In nested loops the inner loop completes all of its iterations for every single iteration of the outer loop. When both bounds are fixed, the total iteration count is the product of the two. When the inner bound depends on the outer variable, as in for (int j = 0; j < i; j++), the pattern becomes triangular and the total is a running sum rather than a product.
Name what each loop controls before tracing, then count inner executions as the product.
Common error
Using the outer loop variable inside the inner body where the inner one was intended.
Worked example
Java
int count = 0;
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= row; col++) count++;
}
System.out.println(count);Output
6The inner loop executes 1 + 2 + 3 times rather than 3 times for every row.
Exercises
3.3.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) System.out.print(r + c);
System.out.println();
}Show solution
Output
012
123Each row resets c to zero; r + c is numeric addition before printing.
3.3.2 · Write code
Write nested loops that print three rows of stars: one star, then two, then three. Use print inside the inner loop and println after it.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
for (int row = 1; row <= 3; row++) {
for (int col = 0; col < row; col++) System.out.print("*");
System.out.println();
}