Unit 2 Cycle 2 Day 24: Complex Nested Loop Trace
Share
Complex Nested Loop Trace
Section 2.12 — Nested Loops
Key Concept
Complex nested loop traces combine variable-dependent bounds, accumulators, and conditional logic across both loops. The most challenging AP exam nested loop problems have the inner loop's start or end value depend on the outer variable: for (int j = 0; j < i; j++). This creates a triangular iteration pattern where each outer iteration runs a different number of inner iterations. A complete trace table is essential — label columns for both loop variables, the condition result, and any accumulator.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (C) 30
i=1: j runs 1 time, adds 1*1=1. i=2: j runs 2 times, adds 2*2=4. i=3: j runs 3 times, adds 3*3=9. i=4: j runs 4 times, adds 4*4=16. Sum = 1+4+9+16 = 30.
Why Not the Others?
(A) 10 = 1+2+3+4, which would be adding i once per outer iteration. But the inner loop adds i multiple times.
(B) 20 would be sum if inner added j instead of i each time: 1+(1+2)+(1+2+3)+(1+2+3+4)=20.
(D) 40 would be 4 * 10, which does not match the pattern.
Common Mistake
The inner loop adds i (not j) each time. When j runs i times, it adds i exactly i times, giving i*i. The total is the sum of squares: 1+4+9+16=30.
AP Exam Tip
Watch which variable is being accumulated in nested loops. Adding the outer variable (i) vs the inner variable (j) gives very different results.