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.
Use using System.Collections.Generic; at the top of the C# file, before its class definitions. Place the following statements inside an existing method.
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.
| Value supplied | totalGoals afterward | scoringRounds afterward |
|---|---|---|
| 2 | 2 | 1 |
| 0 | 2 | 1 |
| 3 | 5 | 2 |
| No next item | 5; body skipped | 2; body skipped |
If either accumulator were reset to 0 inside the loop, earlier passes would be lost. With an empty list, both initialized results remain 0.