How do you loop through 2d array in c#


How do you loop through 2d array in c#

To loop through a two-dimensional (2D) array in C#, you can use nested loops. The outer loop iterates over the rows, and the inner loop iterates over the columns of each row.

Here's an example:

csharp

int[,] array = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

for (int i = 0; i < array.GetLength(0); i++) {

for (int j = 0; j < array.GetLength(1); j++) {

Console.Write(array[i, j] + " ");

}

Console.WriteLine();

}

`

In this example:

- `array.GetLength(0)` gives the number of rows in the array.

- `array.GetLength(1)` gives the number of columns in each row.

The outer loop (`for (int i = 0; i < array.GetLength(0); i++)`) iterates over each row, and the inner loop (`for (int j = 0; j < array.GetLength(1); j++)`) iterates over each column in that row. The `Console.Write(array[i, j] + " ");` statement prints the value at position `(i, j)` and a space.

After printing all elements in one row, `Console.WriteLine();` is used to move to the next line for readability.




Login to Continue, We will bring you back to this content 0



For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email Address[email protected]