2.4.9 Accumulators In Lists

Accumulators In Lists

The Wildcats coach needs both total goals and the number of rounds in which the team scored. Use separate accumulators because those questions measure different things.

Explore the idea
Total values and count matching items

Use using System.Collections.Generic; at the top of the C# file, before its class definitions. Place the following statements inside an existing method.

Accumulate across the score list
List<int> roundGoals = new List<int>();
roundGoals.Add(2);
roundGoals.Add(0);
roundGoals.Add(3);
int totalGoals = 0;
int scoringRounds = 0;

foreach (int goals in roundGoals)
{
    totalGoals = totalGoals + goals;

    if (goals > 0)
    {
        scoringRounds = scoringRounds + 1;
    }
}

Initialize both accumulators before the loop. Each pass adds the score to totalGoals. Only a positive score adds one to scoringRounds.

Track both results
Value supplied totalGoals afterward scoringRounds afterward
2 2 1
0 2 1
3 5 2
No next item 5; body skipped 2; body skipped
Choose what to accumulate

If either accumulator were reset to 0 inside the loop, earlier passes would be lost. With an empty list, both initialized results remain 0.

Predict and check