
Think together · Start with a story
A girl reads 2, 3, and 6 pages over three days. What is her average per day? The robot first adds the page counts together.
Break down the process
- StartTotal is 0
- AccumulateAdd 2 and 3
- Finish the total2 + 3 + 6 = 11
- Find the average11 divided by 3
The average is the total sum divided by the number of values.
01What is accumulation?
Accumulation means keeping a running total and adding one value at a time.
02How do you find the total?
long long sum = 0;
for (int i = 0; i < 4; i++) {
sum += a[i];
}
sum=0
sum=10
sum=30
sum=100
03Why does sum often start at 0?
Because 0 is the identity for addition:
0 + x = x
Starting at 0 does not change the first value that gets added.
04How do you calculate the average?
Average = total sum ÷ number of elements.
double average = static_cast<double>(sum) / 4;
Here, sum is converted to double to ensure floating-point division.
05Why not just write sum / 4?
If sum and 4 are both integers, C++ uses integer division.
5 / 2 // result is 2, not 2.5
06Why use long long for sum sometimes?
Even if each array element fits in an int, the total of many elements may exceed the range of int.
In programming contests, estimate the maximum total by multiplying the largest possible element by the number of elements, then choose a type.
What you have learned
- Use an accumulator to find a sum.
- The initial value for addition is usually 0.
- The average is the total divided by the count.
- Integer division drops the fractional part, so averages often need floating-point arithmetic.
- A total may be much larger than one element, so consider the integer range.
Next: What Is an Array Out-of-Bounds Error?
Your turn to try
If you use only integers to calculate 11 / 3, what do you get?
Ready? Open to see the explanation
You get 3, not about 3.67. Use 11.0 / 3 for floating-point arithmetic, then display as many decimal places as needed.