Skip to main content

Accumulators

An accumulator is a numeric variable (e.g. int) that builds up a result, usually a total.

// what your comfy with atm
total = total + amount;
// shorthand (programmers are lazy)
total += amount;
// alternatively, if the amount is always 1
total++;

Accumulators usually start at 0, but the right starting value depends on the operation.

Example 1: Average Calculator​

A user enters numbers one at a time and types stop when finished. The program then displays the average, which is the sum of the numbers divided by how many were entered.

Pseudocode​

  1. Set count (int) and total (double) to 0.
  2. Ask the user for a number or "stop", and read the input.
  3. While the input is not "stop":
    • Add 1 to count.
    • Add the number to total.
    • Ask for and read the next input.
  4. If count is greater than 0, display total / count. Otherwise, tell the user no numbers were entered.

C# Code​

int count = 0;
double total = 0.0;

Console.Write( "Enter a number, or 'stop' to see the average: ");
string input = Console.ReadLine();

while (input != "stop")
{
count++;
total += double.Parse(input);

Console.Write("Enter a number, or 'stop' to see the average: ");
input = Console.ReadLine();
}

if (count > 0)
{
double average = total / count;
Console.WriteLine($"The average is {average}");
}
else
{
Console.WriteLine("No numbers were entered.");
}

Note: total / count already produces a double because total is a double, so count doesn't need to be explicitly converted.