AP CSP Day 37: Accumulator Pattern | Cycle 2

Key Concepts

Accumulator initialization errors cause systematic incorrect results: initializing a sum accumulator to 1 instead of 0 adds 1 to every computed total, and initializing a product accumulator to 0 instead of 1 makes every product zero. A subtler error is resetting the accumulator inside the loop rather than before it, restarting the accumulation on every iteration. AP CSP Cycle 2 accumulator questions present pseudocode with one of these initialization or placement errors and ask students to determine the incorrect output and explain the fix.

📚 Study the Concept First (Optional) Click to expand ▼

Accumulator Bugs: Wrong Initialization

Wrong Starting Value

A sum accumulator initialized to 1 instead of 0 adds 1 to every computed sum. A product accumulator initialized to 0 instead of 1 makes every product 0 regardless of input. The initial value is as important as the accumulation logic.

Reset Inside Loop

Initializing the accumulator inside the loop body resets it to the starting value on every iteration, discarding all previous work. The accumulator initialization must appear before the loop.

Common Trap: Focusing on the loop body logic and overlooking the initialization. The bug is often in the single line before the loop, not in the iteration logic itself.
Exam Tip: Identify the accumulator variable in the pseudocode before tracing. Verify its initial value and its location relative to the loop. These two checks catch the vast majority of accumulator bugs.
Big Idea 3: Algorithms & Programming
Cycle 2 • Day 37 Practice • Hard Difficulty
Focus: Accumulator Pattern

Practice Question

What is displayed after the following code runs?

nums ← [4, 7, 2, 9, 1, 6]
result ← 0
FOR EACH n IN nums
{
   IF n MOD 2 = 1
   {
      result ← result + n
   }
}
DISPLAY(result)
Why This Answer?

The code accumulates only odd numbers (n MOD 2 = 1). Checking each: 4 is even (skip), 7 is odd (add), 2 is even (skip), 9 is odd (add), 1 is odd (add), 6 is even (skip). Sum of odds: 7 + 9 + 1 = 17.

Why Not the Others?

A) 29 is the sum of all elements (4+7+2+9+1+6), not just the odd ones. B) 12 is the sum of even elements (4+2+6). D) 22 does not match any valid subset sum.

Common Mistake
Watch Out!

Students either sum all elements without applying the MOD filter, or confuse MOD 2 = 1 (odd) with MOD 2 = 0 (even), computing the sum of even numbers instead.

AP Exam Tip

When you see an accumulator inside a loop with a condition, identify two things separately: what gets added (the accumulator update) and when it gets added (the filter condition).

Keep Practicing!

Consistent daily practice is the key to AP CSP success.

AP CSP Resources Get 1-on-1 Help
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.