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
- Set
count(int) andtotal(double) to 0. - Ask the user for a number or "stop", and read the input.
- While the input is not "stop":
- Add 1 to
count. - Add the number to
total. - Ask for and read the next input.
- Add 1 to
- If
countis greater than 0, displaytotal / 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 / countalready produces adoublebecausetotalis adouble, socountdoesn't need to be explicitly converted.