C# - Multidimensional Arrays



C# allows multidimensional arrays, which are also called rectangular arrays. If you want to insert the data into a tabular form, similar to a table with rows and columns, it's important to understand how to work with multidimensional arrays.

Declaring Multidimensional Array

You can declare a multidimensional array by specifying the number of dimensions in square brackets. For example, a two-dimensional array of strings can be declared as −

string[,] names;

Similarly, a three-dimensional array of integers can be declared as −

int[,,] m;

Two-Dimensional Arrays

The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional array is a list of one-dimensional arrays.

A 2-dimensional array can be thought of as a table, which has x number of rows and y number of columns. Following is a 2-dimensional array, which contains 3 rows and 4 columns −

Two Dimensional Arrays in C#

Thus, every element in the array a is identified by an element name of the form a[ i , j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in array a.

Initializing Two-Dimensional Arrays

Multidimensional arrays may be initialized by specifying bracketed values for each row. The Following array is with 3 rows and each row has 4 columns.

int [,] a = new int [3,4] {
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

Accessing Two-Dimensional Array Elements

An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array. For example,

int val = a[2,3];

The above statement takes 4th element from the 3rd row of the array. You can verify it in the above diagram.

Example

Let us create a basic example to demonstrate the uses of the two-dimensional array −

using System;
namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         /* an array with 5 rows and 2 columns*/
         int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
         int i, j;
         
         /* output each array element's value */
         for (i = 0; i < 5; i++) {
            
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
            }
         }
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following result −

a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

Finding Size of a Two-Dimensional Array

You can find the total number of elements in a two-dimensional array using the Length property.

Here is a simple example of how to get the total number of elements in a two-dimensional array:

int[,] matrix = new int[3, 4];  
int totalElements = matrix.Length;

Example

The following example demonstrates how to find the total elements in a two-dimensional array in C#:

using System;
namespace Ex2DArrayLength {
   class ArraySize {
      static void Main(string[] args) {
         int[,] matrix = new int[3, 4];  
         
         Console.WriteLine("Total elements: " + matrix.Length);
         Console.ReadKey();
      }
   }
}

When executed, this program outputs:

Total elements: 12

Getting Size of Each Dimension in a Multidimensional Array

You can get the size of each dimension in a multidimensional array using the GetLength() method.

Syntax

Here is the syntax to get the dimensions −

int rows = array.GetLength(0); // Returns the number of rows
int cols = array.GetLength(1); // Returns the number of columns

Example

The following example demonstrates how to get the dimensions of a multidimensional array −

using System;
namespace ExGettingDimensions {
   class MyArray {
      static void Main(string[] args) {
         // Declare and initialize a 3x4 matrix
         int[,] matrix = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
         };

         // Get dimensions
         int rows = matrix.GetLength(0);
         int cols = matrix.GetLength(1);

         // Display the dimensions
         Console.WriteLine("Number of Rows: " + rows);
         Console.WriteLine("Number of Columns: " + cols);

         Console.ReadKey();
      }
   }
}

When executed, this program outputs:

Number of Rows: 3
Number of Columns: 4

Sorting a Two-Dimensional Array

C# does not provide any built-in method for sorting. You can sort the elements of a two-dimensional array by sorting its rows or columns. You can use loops and Array.Sort() to sort each row.

Example

The following example demonstrates how to sort each row of a two-dimensional array:

using System;

class Program {
    static void Main() {
        int[,] array = {
            {3, 1, 4},
            {9, 2, 8},
            {5, 7, 6}
        };

        // Sorting each row
        for (int i = 0; i < array.GetLength(0); i++) {
            int[] row = new int[array.GetLength(1)];

            // Copy row to 1D array
            for (int j = 0; j < array.GetLength(1); j++) {
                row[j] = array[i, j];
            }

            // Sort the row
            Array.Sort(row);

            // Copy back sorted row to 2D array
            for (int j = 0; j < array.GetLength(1); j++) {
                array[i, j] = row[j];
            }
        }

        // Display sorted array
        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();
        }
    }
}

When executed, this program outputs:

1 3 4
2 8 9
5 6 7
Advertisements