The coach wants to read every score in the current sequence. A foreach loop supplies each list item in index order without a manually managed index.
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 roundsVisited = 0;
foreach (int goals in roundGoals)
{
roundsVisited = roundsVisited + 1;
}The iteration variable goals receives 2, then 0, then 3. The body runs three times, even though one score is zero. The counter finishes at 3.
| Next item available? | Value supplied | roundsVisited after body |
|---|---|---|
| Yes | 2 | 1 |
| Yes | 0 | 2 |
| Yes | 3 | 3 |
| No | No value supplied | 3; body skipped |
For an int list, the iteration variable supplies a value and cannot be assigned a new value inside the loop. A Player iteration variable can reach and update a Player field; changing that object’s field does not add or remove list entries.