AP CSP Day 7: Accumulator Pattern
Share
The accumulator pattern initializes a variable to a starting value (often 0 or an empty list) before a loop, then updates it each iteration to build a result. This pattern appears in algorithms that compute sums, products, counts, or concatenated strings across a dataset. AP CSP exam questions testing the accumulator pattern frequently ask students to identify what value the accumulator holds after all iterations complete. Recognizing this pattern quickly is a strong exam strategy.
📚 Study the Concept First (Optional) Click to expand ▼
The Accumulator Pattern
What Is an Accumulator?
An accumulator is a variable initialized before a loop that collects a running result across iterations. Common accumulators compute sums, products, counts, or build strings and lists.
Real-World Analogy
A shopping cart total starts at \$0 (initialization). As you add each item, its price is added to the running total (update per iteration). The final total after all items is your result.
Practice Question
What is displayed after the following code runs?
total ← 0
nums ← [4, 7, 3]
FOR EACH n IN nums
{
total ← total + n
}
DISPLAY(total)The accumulator pattern initializes total to 0 and adds each element during traversal. After processing: 0+4=4, 4+7=11, 11+3=14. The final accumulated value is 14.
A) 4 is total after only the first iteration. B) 7 is just the second element, not the running total. D) 3 is just the last element, not the accumulated sum.
Students sometimes display only the last element processed rather than the running total, forgetting that the accumulator carries forward across iterations.
The accumulator pattern has two key parts: initialize a variable before the loop and update it inside the loop. The final value reflects all iterations combined.
Keep Practicing!
Consistent daily practice is the key to AP CSP success.
AP CSP Resources Get 1-on-1 Help