C# Two Dimensional Array Example

In this source code example, we will demonstrate how to create a two-dimensional array in C#.

If we need two indexes to access an element in an array then we have a two-dimensional array.

C# Two Dimensional Array Example

using System;

public class ArrayDemo
{
    public static void Main(string[] args)
    {
                //initializing 2D array
       int[ , ] numbers = {{2, 3}, {4, 5}};
 	 
        // access first element from the first row
       Console.WriteLine("Element at index [0, 0] : "+numbers[0, 0]);
  	 
        // access first element from second row
       Console.WriteLine("Element at index [1, 0] : "+numbers[1, 0]);
       
       Console.WriteLine(" access 2D using for loop ");
        int d1 = numbers.GetLength(0);
        int d2 = numbers.GetLength(1);
        
        for (int i=0; i<d1; i++)
        {
            for (int j=0; j<d2; j++)
            {
                Console.WriteLine(numbers[i, j]);
            }
        }

       Console.WriteLine(" access 2D using foreach loop ");
       
       foreach (var val in numbers)
       {
            Console.WriteLine(val);
       }

    }
}

Output:

Element at index [0, 0] : 2
Element at index [1, 0] : 4
 access 2D using for loop 
2
3
4
5
 access 2D using foreach loop 
2
3
4
5

We declare and initialize a two-dimensional array in one statement. Note the comma inside the square brackets:

       int[ , ] numbers = {{2, 3}, {4, 5}};

Access a two-dimensional array using for loop:

       Console.WriteLine(" access 2D using for loop ");
        int d1 = numbers.GetLength(0);
        int d2 = numbers.GetLength(1);
        
        for (int i=0; i<d1; i++)
        {
            for (int j=0; j<d2; j++)
            {
                Console.WriteLine(numbers[i, j]);
            }
        }
Access a two-dimensional array using foreach loop:

       Console.WriteLine(" access 2D using foreach loop ");
       
       foreach (var val in numbers)
       {
            Console.WriteLine(val);
       }


Comments