Unit 2 Cycle 1 Day 19: Nested Loop Output Pattern

Unit 2 Foundation (Cycle 1) Day 19 of 28 Foundation

Nested Loop Output Pattern

Section 2.12 — Nested Loops

Key Concept

Nested loops have an inner loop that completes all its iterations for each single iteration of the outer loop. If the outer loop runs m times and the inner loop runs n times, the inner body executes m * n times total. Output pattern questions ask you to determine what is printed, which requires tracking both loop variables simultaneously. Draw a table with outer variable values in rows and inner variable values in columns to visualize the pattern.

Consider the following code segment.

for (int r = 1; r <= 3; r++) { for (int c = 1; c <= r; c++) { System.out.print("* "); } System.out.println(); }

What is printed as a result of executing the code segment?

Answer: (A) * * * * * *

r=1: inner loop runs 1 time (c=1), prints "* ". Newline. r=2: inner runs 2 times, prints "* * ". Newline. r=3: inner runs 3 times, prints "* * * ". Triangle pattern.

Why Not the Others?

(B) The inner loop runs c <= r times, not a fixed 3 times. Each row has a different number of stars.

(C) This would be an inverted triangle (r going from 3 down to 1), but the outer loop goes from 1 to 3.

(D) Each row would have only 1 star if the inner loop always ran once, but it runs r times.

Common Mistake

In nested loops, the inner loop's bounds often depend on the outer loop variable. Here c <= r means row 1 has 1 star, row 2 has 2, row 3 has 3.

AP Exam Tip

For nested loop output questions, trace the outer loop first. For each outer iteration, determine how many times the inner loop runs, then write the output.

Review this topic: Section 2.12 — Nested Loops • Unit 2 Study Guide

More Practice

Related FRQs

Back to blog

Leave a comment

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