2.2.16 Traversing an Array With a for Loop

Visit Every Soccer Score with a for Loop

To traverse an array, let a loop index select one element per pass. Start at zero and continue while the index is below Length. This visits every allocated position once.

Explore the Soccer Example

For this training exercise, the coach adds one practice goal to every recorded round score. Element replacement has already been introduced; this loop applies it to every position.

Visit Every Soccer Score with a for Loop
int[] roundGoals = { 2, 0, 3 };

for (int index = 0; index < roundGoals.Length; index++)
{
    roundGoals[index] = roundGoals[index] + 1;
}
Understand the Code

Use index zero for the first element

The local index begins at 0. The condition compares it with Length, which is 3. The first true check selects roundGoals[0].

The assignment reads its score 2, adds one, and stores 3 back in that same position.

Advance to the next position

The header update index++ adds one after the body. Indexes 1 and 2 are then processed in order. Each access uses the current index, so it targets a different score.

Stop before an invalid access

After index 2 is processed, the update makes index 3. The condition 3 < 3 is false. The body is skipped, so it never tries roundGoals[3].

An empty array needs no special body case

If the array has zero elements, the first comparison is 0 < 0. It is false and the body is skipped.

The same header works without manually copying an element count into the bound.

Use the index in the body, not a fixed position

The header alone does not guarantee every score is processed. The body must use the changing index. Writing roundGoals[0] = roundGoals[0] + 1; there would repeatedly change only the first score.

Trace both the index and the selected element. In the correct version they move together through positions 0, 1, and 2, leaving every position updated exactly once.

Check the Values
Worked soccer example
Index at test Condition Element update
0 True 2 becomes 3
1 True 0 becomes 1
2 True 3 becomes 4
3 False No element access
Try a Small Change
Predict the Result
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.

Visit Every Soccer Score with a for Loop.
Visit Every Soccer Score with a for Loop
  • New
  • Changed
  • Removed

The diagram begins with the three-score array. Each true route replaces the element at the current index, advances the index, and returns to the condition. At index 3, the false route exits without another element access.