Multidimensional Array

0
  1. 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];
  2. 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 } };
  3. Accessing Elements:

    • Elements are accessed using row and column indices.

    • Example:

      int element = matrix[1, 2]; // Accessing element in the second row, third column
  4. 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]);
            }
        }
  5. 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];
          }
      }

Leave a Reply

Your email address will not be published. Required fields are marked *