Jagged Arrays

Programming C#

A two dimensional array has a rectangular size (f.e: 5x5 elements). A jagged array offers way more flexibility. With a jagged array every row can have a different size:

int[][] jaggedArr =
{
    new[] { 1, 2, 3 },
    new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 },
    new[] { 7, 12 }
};

We can iterate through a jagged array with a nested loop. More or less the same like for a standard (fixed) array but be shure to measure the current row size for each inner loop:

for (int row = 0; row < jaggedArr.Length; row++)
{
    for (int col = 0; col < jaggedArr[row].Length; col++)
    {
        Console.WriteLine($"row {row}, column {col}, value: {jaggedArr[row][col]}");
    }
}

This will produce this output:

row 0, column 0, value: 1
row 0, column 1, value: 2
row 0, column 2, value: 3
row 1, column 0, value: 1
row 1, column 1, value: 2
row 1, column 2, value: 3
row 1, column 3, value: 4
row 1, column 4, value: 5
row 1, column 5, value: 6
row 1, column 6, value: 7
row 1, column 7, value: 8
row 1, column 8, value: 9
row 2, column 0, value: 7
row 2, column 1, value: 12