🔷 C#

Arreglos bidimensionales en C# (.NET 6): guía detallada

Two-Dimensional Arrays in C#

Imagine a chessboard. It has rows and columns. Or imagine the multiplication table you learned in school. A regular array is like a list of books on one shelf. A two-dimensional array is like a whole bookcase with several shelves! On each shelf (row) there are several books (elements).

In programming, two-dimensional arrays help store data that is conveniently represented as a table: an island map, a cinema seating chart, game results, a table of temperatures by day of the week.

How to declare a two-dimensional array?

In C#, a two-dimensional array is declared using a comma inside square brackets: [,]. The first number in the brackets is the number of rows, the second is the number of columns.

// Creating an empty array of 3 rows by 4 columns (e.g., 3 rows of 4 seats in a cinema)
int[,] cinema = new int[3, 4];

You can immediately fill the array with data:

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

Here we have 3 rows and 3 columns. Note: each row is its own set of numbers in curly braces.

How to access an element?

To get or change an element, you need to specify its row index and column index. Remember: counting starts from zero!

int[,] map = new int[2, 3]; // 2 rows, 3 columns

map[0, 0] = 5;  // First row, first column
map[0, 1] = 10; // First row, second column
map[1, 2] = 15; // Second row, third column

Console.WriteLine(map[0, 1]); // Outputs 10

How to iterate through all elements (double loop)?

To iterate through all elements of a two-dimensional array, two nested for loops are used. The first loop goes through the rows, the second goes through the columns.

int[,] matrix = new int[,] { {1, 2}, {3, 4} };

for (int i = 0; i < matrix.GetLength(0); i++) // i — row number
{
    for (int j = 0; j < matrix.GetLength(1); j++) // j — column number
    {
        Console.Write(matrix[i, j] + " ");
    }
    Console.WriteLine(); // Move to a new line after each row of the table
}

Important! GetLength(0) gives the number of rows, and GetLength(1) gives the number of columns.

Analysis of typical tasks

Task 1: Creating a hall layout (keyboard input)

Imagine we are creating a cinema hall layout. First, we ask the user for the number of rows and seats, and then we fill the array.

Console.Write("Enter the number of rows: ");
int rows = int.Parse(Console.ReadLine());
Console.Write("Enter the number of seats in a row: ");
int cols = int.Parse(Console.ReadLine());

int[,] hall = new int[rows, cols];

// Fill the array (e.g., with all ones — free seats)
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        hall[i, j] = 1; // 1 — seat is free
    }
}

// Output the hall layout
Console.WriteLine("Hall layout:");
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < cols; j++)
    {
        Console.Write(hall[i, j] + " ");
    }
    Console.WriteLine();
}

Task 2: Finding the maximum element (e.g., the strongest earthquake)

Suppose we have a 2x2 array with earthquake magnitudes. We need to find the strongest one.

double[,] earthquakes = new double[2, 2];
Console.WriteLine("Enter 4 magnitude values:");
for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 2; j++)
    {
        earthquakes[i, j] = double.Parse(Console.ReadLine());
    }
}

double maxMagnitude = earthquakes[0, 0];
for (int i = 0; i < 2; i++)
{
    for (int j = 0; j < 2; j++)
    {
        if (earthquakes[i, j] > maxMagnitude)
        {
            maxMagnitude = earthquakes[i, j];
        }
    }
}
Console.WriteLine($"Maximum magnitude: {maxMagnitude}");

Common beginner mistakes

  • Array index out of bounds. If the array is 3x3, then the row and column indices are from 0 to 2. Accessing arr[3, 0] will cause an error.
  • Confusing rows and columns. The first index is always the row, the second is the column.
  • Forgetting the nested loop. To fill or output a two-dimensional array, you need two loops, one inside the other.
  • Using Length instead of GetLength(). The Length property returns the total number of elements (rows * columns), not the number of rows or columns separately.

Final example: Captain Silver's treasure map

Captain Silver hid a treasure on an island. We have a 3x3 map, where 'X' is the treasure and 'O' is an empty spot. Let's write a program that finds the treasure's coordinates.

char[,] island = new char[3, 3];
Console.WriteLine("Enter the island map (3 lines of 3 characters, X or O):");

for (int i = 0; i < 3; i++)
{
    string line = Console.ReadLine(); // Read an entire line
    for (int j = 0; j < 3; j++)
    {
        island[i, j] = line[j]; // Write each character into the array
    }
}

bool found = false;
for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
    {
        if (island[i, j] == 'X')
        {
            Console.WriteLine($"Treasure found! Row: {i + 1}, Seat: {j + 1}");
            found = true;
        }
    }
}

if (!found)
{
    Console.WriteLine("Treasure not found. Captain Silver tricked us!");
}

Two-dimensional arrays are a powerful tool. They allow you to work with tabular data, maps, and game fields. The main thing is to remember: the first index is the row, the second is the column, and always use two loops for traversal. Good luck with programming!