C# Foundations · Lesson 30

Nested loops for rows and columns

Keep coordinates and loop bounds explicit while processing a small matrix.

How it works

A nested loop expresses work with more than one independent coordinate. In a rectangular table, the outer loop commonly chooses a row and the inner loop walks its columns. Give those coordinates meaningful names so that a reader can tell which dimension each bound belongs to. A mistake in a loop bound can otherwise be difficult to spot when both dimensions happen to have the same size.

A rectangular multidimensional array reports the size of each dimension through GetLength. A jagged array is different: each row is its own array and can have a different length. Choose the representation that matches the data instead of treating every table as a square grid. This example uses a rectangular table with two rows and three columns.

Walk through the example. Each outer-loop iteration starts a new row total at zero. The inner loop adds the three values in that row and contributes each value to the overall total. Resetting the row total inside the outer loop is essential; the overall total deliberately lives outside it. The output therefore reports six for the first row, fifteen for the second, and twenty-one overall.

Watch the boundary. Changing the inner bound to the number of rows would silently skip a column in this particular table. A square test case would hide that bug. Likewise, declaring the row total outside the outer loop would make the second row's result cumulative. Test dimensions that differ, and trace variable lifetimes alongside index values.

Practice independently. Build a three-by-two table of quantities and print both row totals and column totals. Use unequal dimensions so that exchanging the bounds fails visibly. Add a table containing zeros and negative adjustments. Finally explain how the loops would change for a jagged array whose second row has only one element, and which rectangular assumptions would no longer be valid.

A working example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;

int[,] table = { { 1, 2, 3 }, { 4, 5, 6 } };
int overall = 0;
for (int row = 0; row < table.GetLength(0); row++)
{
    int rowTotal = 0;
    for (int column = 0; column < table.GetLength(1); column++)
    {
        rowTotal += table[row, column];
        overall += table[row, column];
    }
    Console.WriteLine($"row{row}:{rowTotal}");
}
Console.WriteLine($"all:{overall}");

Expected output

row0:6
row1:15
all:21
Try this
Use each dimension’s actual bound and reset per-row state at the right scope.