-
syntax of 2D Arrays:
-
In C#, a 2D array is declared using the
[,]
syntax. -
Syntax:
type[,] arrayName = new type[rowSize, columnSize];
-
Example:
int matrix[3][4];
-
-
Initialization of 2D Arrays:
-
2D arrays can be initialized during declaration or later using nested loops.
-
Example:
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
-
-
Accessing Elements:
-
Elements are accessed using row and column indices.
-
Example:
int element = matrix[1, 2]; // Accessing element in the second row, third column
-
-
Traversing a 2D Array:
-
Nested loops are commonly used for traversing the entire array.
-
Example:
for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { Console.WriteLine(matrix[i, j]); } }
-
-
-
Common Operations:
-
Sum of all elements:
int sum = 0; for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { sum += matrix[i, j]; } }
-
