Unit 2 Cycle 2 Day 18
Share
Practice Question
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= row; col++) {
System.out.print(col);
}
System.out.println();
}
The correct answer is A) 1 / 12 / 123 (three lines of output)
Let's trace through the nested loops:
When row = 1:
- Inner loop runs with col = 1 (since col <= 1)
- Prints: 1
- println() creates new line
When row = 2:
- Inner loop runs with col = 1, then col = 2 (since col <= 2)
- Prints: 12
- println() creates new line
When row = 3:
- Inner loop runs with col = 1, 2, then 3 (since col <= 3)
- Prints: 123
- println() creates new line
The key is that the inner loop's bound is col <= row, so it prints col values from 1 up to the current row number.
B) 1 / 11 / 111 - This would be correct if the inner loop printed row instead of col. The code prints col, not row.
C) 123 / 123 / 123 - This would require the inner loop to always run 3 times (col <= 3), not col <= row. The bound changes each iteration of the outer loop.
D) 111 / 222 / 333 - This confuses what variable is being printed and would require printing row multiple times per inner loop iteration.
Students often confuse which variable is being printed (col vs row) and miss that the inner loop's bound changes with each outer loop iteration. The pattern col <= row creates a triangular output where each row has one more number than the previous.
For nested loops, trace the outer loop first, then for each value of the outer variable, trace the entire inner loop. Pay close attention to which variable is printed and what determines the inner loop's bound. Drawing a quick table can help visualize nested loop execution.
Keep Practicing!
Cycle 2 questions prepare you for the hardest AP CSA exam questions.
Study Games Practice FRQs