Unit 2 Cycle 2 Day 9: Nested Loop with Break Pattern

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

Nested Loop with Break Pattern

Section 2.12 — Nested Loops

Key Concept

While Java does not have a break statement on the AP CSA exam, the equivalent pattern uses a boolean flag variable. Instead of while (condition) { if (found) break; }, the AP exam pattern is boolean found = false; while (condition && !found) { if (target) found = true; }. Nested loops with early termination require a flag that the outer loop also checks. Understanding this pattern helps you trace complex search algorithms where the loop exits before reaching its natural end.

Consider the following code segment.

boolean found = false; for (int i = 0; i < 5 && !found; i++) { for (int j = 0; j < 5 && !found; j++) { if (i + j == 4) { found = true; System.out.println(i + " " + j); } } }

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

Answer: (A) 0 4

The loops search for the first pair where i+j=4. i=0: j=0(0), j=1(1), j=2(2), j=3(3), j=4(4). i+j=4 when j=4. Prints 0 4. found=true stops both loops.

Why Not the Others?

(B) The outer loop starts at i=0, so i=0 is checked first with all j values.

(C) (2,2) satisfies i+j=4, but (0,4) is found first since i=0 is checked before i=2.

(D) (1,3) satisfies i+j=4, but (0,4) is found first.

Common Mistake

Using a boolean flag in the loop condition (&& !found) creates an early exit pattern. The first matching pair stops all iteration. The order of iteration determines which pair is found first.

AP Exam Tip

When nested loops use a flag for early termination, the first valid result depends on the traversal order. Outer loop values are checked first, then inner loop values.

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.