2d Arrays
Lesson 22Author : Afrixi
Last Updated : February, 2023
A 2D array is an array of arrays, where each array is a row of values. In C#, you can create a 2D array by declaring an array variable with two dimensions, like this:
int[,] myArray = new int[3, 4];
This creates a 2D array with three rows and four columns. You can assign values to the array like this:
myArray[0, 0] = 1;
myArray[0, 1] = 2;
myArray[0, 2] = 3;
myArray[0, 3] = 4;
myArray[1, 0] = 5;
myArray[1, 1] = 6;
myArray[1, 2] = 7;
myArray[1, 3] = 8;
myArray[2, 0] = 9;
myArray[2, 1] = 10;
myArray[2, 2] = 11;
myArray[2, 3] = 12;
This assigns the values 1 through 12 to the 2D array.
You can also initialize a 2D array with values using an array initializer:
int[,] myArray = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
This creates the same 2D array with the same values as in the previous example.
You can iterate through a 2D array using nested loops. For example, to print out the values in the array, you can use the following code:
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
Console.Write(myArray[i, j] + " ");
}
Console.WriteLine();
}
This will print out the values in the 2D array row by row.