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.
numStudents
by 1", and "updates an aardvark variable namedtotal
by the value", you don't need to understand all the words to get the gist. That's the wondrous redundancy of natural language. – Ulcerous