Unit 2 Cycle 1 Day 20: Nested Loop Counting
Share
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.
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.