The Accumulator pattern (summing values)
What you'll learn: How to use a single variable to "collect" and total up values throughout a loop.
The Piggy Bank Analogy
Imagine you have an empty piggy bank. Every day, you find some loose change and drop it inside. The bank doesn't care if you add a penny today or a dollar tomorrow; its only job is to hold the running total. In programming, we call this the Accumulator Pattern.
You start with a variable set to zero, and as you loop through a set of data, you "toss" each new value into that variable. By the time the loop finishes, the variable holds the grand total of everything you’ve encountered.
Setting Up the Accumulator
To make this work in C, you need two things:
- Initialization: You must set your total to
0before the loop starts. If you forget, your variable might contain "garbage" data (leftover bits in memory), and your final sum will be nonsensical. - The Update: Inside the loop, you use the
+=operator. This tells C to take the current total, add the new value to it, and save the result back into the total.
Code Example: Summing the first 10 numbers
Here is how we calculate the sum of integers from 1 to 10:
#include <stdio.h>
int main() {
// 1. Initialize the accumulator to zero
int total_sum = 0;
for (int i = 1; i <= 10; i++) {
// 2. Add the current value of i to our running total
total_sum += i;
// Optional: Watch it grow
printf("Adding %d... Current total: %d\n", i, total_sum);
}
printf("Final Grand Total: %d\n", total_sum);
return 0;
}
A Common Pitfall
The most frequent mistake is declaring the accumulator variable inside the loop. If you do that, the variable is destroyed and recreated every time the loop repeats. It’s like emptying the piggy bank and throwing it away every time you put a coin in—you’ll never actually accumulate anything! Always make sure your "bank" is created outside the loop.
Key takeaway
An accumulator is a variable initialized to zero outside a loop that uses += inside the loop to build a running total.