Unit 2 Cycle 2 Day 18

Unit 2, Section 2.12 - Cycle 2
Day 18 Advanced Practice - Harder Difficulty
Focus: Nested Loop Output Tracing

Practice Question

Consider the following code segment:
for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= row; col++) {
        System.out.print(col);
    }
    System.out.println();
}
What is printed when this code segment executes?
Why This Answer?

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.

Why Not the Others?

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.

Common Mistake
Watch Out!

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.

AP Exam Tip

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
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.