2.4.4 foreach Loops

Read Soccer Scores with a foreach Loop

The Wildcats coach wants to add every round score without using the position in the calculation. A foreach loop supplies one element value to its body at a time.

For a one-dimensional array, it visits elements in index order. You write the work for the current element without defining and updating an index yourself.

Name the Current Element
Read one score per foreach pass
int[] roundGoals = { 2, 0, 3 };
int totalGoals = 0;

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

Read the header in parts

The word foreach identifies the loop form. int goals defines the iteration variable that represents the current element value. The word in identifies the array whose elements are supplied.

On successive passes, goals receives 2, then 0, then 3. The body adds each supplied value to the running total.

No element means no body pass

After the third element has been processed, there is no next element and the loop ends. With an empty int array, the body would run zero times and the initialized total would stay zero.

The loop still uses the existing element order; it does not sort scores or skip zero-valued elements.

Compare the Supplied Values with the Total
Three body executions
Pass Value supplied as goals Total before addition Total after addition
1 2 0 2
2 0 2 2
3 3 2 5
Predict Another Sequence
Use the Original Diagram to Check Your Reasoning

The diagram below shows the original example. Compare it with your prediction for the requested change; its pictured values have not been replaced by the practice inputs.

The array supplies 2, 0, and 3 in order. Each value is added once. When no next element remains, the loop exits with totalGoals equal to 5.
Each available element supplies the next body value
  • New
  • Changed
  • Removed

The decision in this conceptual diagram asks whether another element is available. The next-value action represents what foreach supplies automatically.

There is no source-level index++ in this example, so the diagram does not invent one. The total addition is the one explicit statement in the C# body.