What is the difference between a counter and an accumulator?

user1756913 picture user1756913 · Oct 20, 2012 · Viewed 22.2k times · Source

I'm not sure what the difference are, but here are the problems.

Write an assignment statement that updates a counter variable named numStudents by 1. would it be:

numStudents = numStudents + 1

? My other problem is

Write an assignment statement that updates an accumulator variable named total by the value in the sales variable. would it be identical like:

total = total + sales

?

Answer

Alberto Moriconi picture Alberto Moriconi · Oct 20, 2012

There isn't a single, clear, univocal answer to your question.

It may be said that a counter is a variable that is incremented every time a given event is verified (e.g. when iterating an array, every time you encounter the number 5, you could increment a counter by 1).

The notion may be generalized because there are counters that are incremented by 2, or 3, or any value you'd like, on every step; however, the semantics of a counter usually lose sense if the step isn't always the same. It depends on the logic of your program, in the end: if you're keeping track of single and double rooms in an hotel, your numGuests counter could be incremented with steps of 1 and 2 depending on the rooms you're processing at a given moment, however it could be argued that in the end this is just for clarity or brevity, because the result is the same as incrementing it by 1, twice!

An accumulator is, instead, a variable that, for example, stores the sum of the elements of the array (i.e. you have not a fixed step, but the increment varies based on the elements you encounter).

The notion may be generalized for a list of items, applying a given function f repeatedly to the actual value of the accumulator and the next item of the list, saving the result in our accumulator. In this way, we have obtained the semantics of the fold high-order function (one of its other names is in fact accumulate). If we limit our analysis to what is called left fold, the accumulator stores at every moment an intermediate result, valid for the subset you already processed.

If you have an accumulator named total with the starting value of 0 and an array which contains the sales for the 12 months of the year, applying this definition with + (addition) as our f, will get you at the n-th step the sales for the first n months of the year.

Your examples look good then, as they're strictly adherent to these definitions of accumulators and counters.