2.2.18 Aggregating Values With a Loop

Overview

Aggregation turns several input values into one result. A loop can sum a Zoo record of daily food amounts. It reads each item, adds it to a running total, and returns or displays the total after every item has been visited.

double[] portions = { 0.5, 0.75, 1.0 };
double total = 0;
for (int i = 0; i < portions.Length; i++)
{
    total += portions[i];
}
Compute One Result from Many Values
Activity diagram for aggregating values with a loop: compute one result from many values.
Compute One Result from Many Values
  • New
  • Changed
  • Removed

The running totals are 0.5, 1.25, and 2.25. Adding only after the loop would lose access to the current index; returning during the first pass would report an incomplete total. The final value is read after the condition becomes false.

If the calculation is a count instead of a sum, add one for each qualifying element. Separate the traversal pattern from the operation performed on each visited item.

Trace the Outcome

Trace an empty array and an array containing one value. In both cases, identify where the final result is available.