Unit 2 Cycle 1 Day 20: Nested Loop Counting

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

Nested Loop Counting

Section 2.12 — Nested Loops

Key Concept

Nested loops for counting require an accumulator variable declared before both loops. Each time the inner loop body executes, the accumulator is updated based on the current values of both loop variables. On the AP exam, you might count how many times a condition is true across all combinations of the two loop variables. The total number of checks equals the product of both loops' iteration counts, but the count only increments when the condition inside is satisfied.

Consider the following code segment.

int total = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { total++; } } System.out.println(total);

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

Answer: (B) 12

Outer loop runs 3 times (i=0,1,2). For each outer iteration, inner loop runs 4 times (j=0,1,2,3). Total increments = 3 * 4 = 12.

Why Not the Others?

(A) 7 = 3 + 4, but nested loops multiply iterations, they do not add them.

(C) 3 is just the number of outer loop iterations.

(D) 4 is just the number of inner loop iterations per outer iteration.

Common Mistake

Nested loops multiply iteration counts, not add them. If the outer loop runs m times and inner runs n times, the total body executions = m * n.

AP Exam Tip

For simple nested loops with independent bounds, total iterations = outer count times inner count. This is critical for understanding algorithm efficiency.

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.