AP® Computer Science A · Unit 2 · Topic 2.9
Accumulators, Counters, and Running Totals
An accumulator is a variable declared outside a loop that keeps a running total or count, updating by one small step each pass instead of resetting.
An accumulator works because it lives outside the loop. You declare it once, before the loop starts, and give it a starting value that will not change the result: 0 for a sum, 0 for a count, 1 for a product. Then each pass through the loop body updates that same variable, usually with total += value or count++. Because the variable was declared outside, it keeps whatever value the last pass left it with. The loop does not rebuild it; it only adds to it. Starting a sum at 0 matters because adding anything to 0 leaves it unchanged on the very first pass, so the first real value gets counted correctly. Start it at 5 instead, and every sum comes out 5 too high.
A counter works the same way but tracks how many times something happened rather than a total amount. You still declare it outside the loop at 0, but instead of adding a changing value, you add 1 whenever some condition is true, like arr[i] % 2 == 0 for counting evens.
This connects to the trace tables you have been filling in: each row shows the accumulator's value after one more pass, so tracing a sum or count is really tracing how one variable changes step by step. It also sets up for loops that compute averages or search for extremes, which just add a division or a comparison on top of this same pattern.
Key terms
- Accumulator
- A variable declared outside a loop that collects a running result, such as a sum or product, across every pass.
- Counter
- A variable that tracks how many times a condition was true, usually incremented by 1 each matching pass.
- Running total
- The accumulator's current value at any point during the loop, before all values have been added.
- Initialization
- Giving the accumulator its starting value before the loop begins, chosen so it does not affect the first update.
Watch it explained
- How it worksHow does one variable outside a loop collect a result the loop keeps adding to?
- Worked exampleTrace a loop that sums 3, 8, 1, 6 and find the accumulator after each number.
- Worked exampleFind the count of even numbers among 4, 7, 10, 3, 8 using a counter inside a loop.
- Common mistakeWhy doesn't declaring the total inside the loop body work?
- Going furtherWhat changes when a product accumulator starts at zero rather than at one?
Check yourself
End of topic.