Unit 2 Cycle 2 Day 14: Nested Loop String Building

Unit 2 Advanced (Cycle 2) Day 14 of 28 Advanced

Nested Loop String Building

Section 2.12 — Nested Loops

Key Concept

Nested loops building strings create complex output patterns. The outer loop typically controls rows or major segments, while the inner loop builds each segment character by character. When println appears inside the outer loop (but after the inner loop), it creates line breaks between segments. The AP exam tests your ability to determine the exact string built by the inner loop for each value of the outer variable, especially when the inner loop's bounds depend on the outer variable.

Consider the following code segment.

String result = ""; for (int i = 1; i <= 4; i++) { for (int j = i; j <= 4; j++) { result += j; } result += "-"; } System.out.println(result);

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

Answer: (A) 1234-234-34-4-

i=1: j=1,2,3,4 → "1234-". i=2: j=2,3,4 → "234-". i=3: j=3,4 → "34-". i=4: j=4 → "4-". Full: "1234-234-34-4-".

Why Not the Others?

(B) The inner loop starts at j=i, not j=1. Each row has fewer numbers as i increases.

(C) This would require j starting at 1 and ending at i, which is the opposite pattern.

(D) j goes from i upward to 4, not downward.

Common Mistake

When the inner loop starts at j = i, each outer iteration produces fewer inner iterations. Row 1 has 4 values, row 2 has 3, row 3 has 2, row 4 has 1.

AP Exam Tip

For nested loop output, create a table showing the inner loop range for each outer iteration. This reveals the pattern immediately.

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.