One running variable, updated a little on every pass, holding the answer at the end. It’s the pattern behind sum, count, max, and average — and behind half the hard questions on the exam. Learn it once; use it all year.
Watch for the “running total” examples — that’s exactly today. Enrolled in our Runestone course? Open it from there so your progress counts.
Still in Programs, and this is the lesson the whole unit leans on. You have loops (3.1–3.3). Put one variable inside a loop and update it each pass, and you can total, count, and track things across many steps. This pattern comes back in every unit that follows.
That running number is an accumulator, and the rhythm never changes: initialize it before the loop, update it inside, use it after. Master those three steps and you’ve got sum, count, max, min, and average — they’re all the same song in a different key.
An accumulator is a variable that builds up a result across the passes of a loop. Every accumulator has the same three positions — and each has a common bug when you get it wrong:
| Step | Where | Sum example |
|---|---|---|
| initialize | before the loop | total = 0 |
| update | inside the loop body | total = total + x |
| use | after the loop | print(total) |
total = 0 inside the loop and it resets to zero every pass, so you only ever
keep the last item. Read the total inside the loop and you print a partial answer over and
over. The three positions are not optional.
total = 0 # initialize for x in [3, 1, 4]: total = total + x # update print(total) # use → 8
total ← 0 FOR EACH x IN [3, 1, 4] { total ← total + x } DISPLAY(total)
Hover or tap a line to light its twin. Trace it: total starts 0, becomes 3, then 4, then 8. The answer, 8, exists only after the loop — inside, it’s always partial.
x; count starts at 0 and
adds 1 (often inside an if); max starts at the first value and keeps
the larger; average is a sum divided by a count. One idea, four variations.
Step through a loop and watch the accumulator update on every pass. Switch between sum and count-evens to see the same pattern do two different jobs.
Five questions. Trace the accumulator pass by pass — write its value after each update — then pick your answer.
Your step count, your bank balance, a video’s view total, a game’s high score, the “items in cart” badge — every one is an accumulator quietly updating as events happen. When you see a number that grows over time, there’s almost always a loop somewhere adding to a running variable.
It scales all the way up: totaling a spreadsheet column, averaging millions of survey responses, counting votes. The idea doesn’t change from three numbers to three billion — only how many times the loop runs. That’s why this humble pattern is the melody of the whole course.
while loop.