2.3.9 Traversing a Two-Dimensional Array

Visit Every Team-and-Round Score

The Wildcats coach wants one total across two teams and three rounds. A two-dimensional traversal must visit all six index pairs exactly once.

Use one loop to choose a team row and another loop inside it to move through that row's round columns. This is a nested loop: the inner loop completes its passes for each outer pass.

Use a Row Loop and a Column Loop
Total both teams across all rounds
int[,] teamGoals = { { 2, 0, 3 }, { 1, 4, 2 } };
int totalGoals = 0;

for (int row = 0; row < teamGoals.GetLength(0); row++)
{
    for (int column = 0; column < teamGoals.GetLength(1); column++)
    {
        totalGoals = totalGoals + teamGoals[row, column];
    }
}

The outer body holds a complete column traversal

The outer loop first selects row 0. Its body defines column at 0 and runs the inner loop through columns 0, 1, and 2.

The addition therefore reads pairs [0,0], [0,1], and [0,2] before the outer update changes the row.

Restart the inner index for the next row

When row becomes 1, execution enters the outer body again. The inner header defines a fresh column local initialized to 0.

It visits [1,0], [1,1], and [1,2]. Starting columns at zero for each row is what prevents the second team's scores from being skipped.

Trace All Six Additions
Row-by-row traversal
Pair visited Score added Running total
[0,0] 2 2
[0,1] 0 2
[0,2] 3 5
[1,0] 1 6
[1,1] 4 10
[1,2] 2 12

The inner body executes six times, but the outer body executes twice. The row label does not advance after each score; it advances after an entire column traversal.

The total is initialized before both loops, so the second row continues adding to the first row's total rather than starting over.

Change One Team's Score
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.

For each of two rows, column starts at zero and visits three elements. The inner return advances columns; the outer return advances rows. The six scores total 12.
Columns repeat inside each selected row
  • New
  • Changed
  • Removed

The inner return path reaches the column condition. Its false exit reaches row++, not the end of the whole activity.

The outer return path re-enters column initialization for the next row. Only the outer false exit ends traversal.