๐ŸŽ“ A1Learner
๐Ÿ”

C# Multidimensional Arrays

A multidimensional array holds values in rows and columns. An int[,] array holds whole numbers in a grid.

Read grid values

Two indexes pick one value from the grid. The first index is the row and the second is the column.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
        Console.WriteLine(grid[0, 0]);
        Console.WriteLine(grid[0, 2]);
        Console.WriteLine(grid[1, 1]);
    }
}

Count rows and columns

GetLength(0) gives the row count. GetLength(1) gives the column count.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
        Console.WriteLine(grid.GetLength(0));
        Console.WriteLine(grid.GetLength(1));
    }
}

Print clean rows

The inner loop builds one row as a string. A space goes between cells and never after the last cell.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
        for (int i = 0; i < grid.GetLength(0); i++)
        {
            string row = "";
            for (int j = 0; j < grid.GetLength(1); j++)
            {
                if (j > 0)
                {
                    row += " ";
                }
                row += grid[i, j];
            }
            Console.WriteLine(row);
        }
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        int[,] seats = { { 1, 0, 1 }, { 0, 1, 1 } };
        int count = 0;
        for (int i = 0; i < seats.GetLength(0); i++)
        {
            for (int j = 0; j < seats.GetLength(1); j++)
            {
                if (seats[i, j] == 1)
                {
                    count++;
                }
            }
        }
        Console.WriteLine("Occupied: " + count);
    }
}

Key points

  • A dimension is one direction in the grid, like rows or columns.
  • The comma inside the brackets marks more than one dimension.
  • Two indexes pick one cell, row first and column second.
  • Use GetLength(0) to get the count of rows.
  • Use GetLength(1) to get the count of columns.
  • A multidimensional array stores a table of values in one variable.

In this example, seats holds 1 for a taken seat and 0 for a free seat. The outer loop visits each row. The inner loop visits each seat in that row. Four cells hold 1, so the print line shows Occupied: 4.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

What does grid.GetLength(0) return for a grid with 2 rows and 3 columns?