2.2.17 Accumulators

Video: Accumulator Loops (7:26)
Overview

An accumulator is a variable that combines values across iterations. Initialize it before the loop, then update it with the current item during each pass. To sum amounts, start at zero so no unrelated value is included.

int[] portions = { 2, 3, 4 };
int total = 0;
for (int i = 0; i < portions.Length; i++)
{
    total += portions[i];
}
Keep a Running Total
Activity diagram for accumulators: keep a running total.
Keep a Running Total
  • New
  • Changed
  • Removed

Total changes from 0 to 2, then 5, then 9. The loop index and total have different jobs: i locates the next item; total remembers the sum so far. The final total is available after the loop exits.

A counter is also a kind of accumulator, but it adds one per event; a sum adds the actual item value. Choose the update that matches the question you are answering.

Trace the Outcome

Trace total after each iteration and distinguish it from the current element. Predict total for an empty array.