Please note, this is a STATIC archive of website technosmarter.com from 20 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
 

C# Multi dimensional arrays | Two dimensional arrays


Unlike another programming, C# supports Multi-dimensional array. In the previous tutorial, we discussed arrays in C# . We created an example for single dimensional array in C#. In this tutorial, we are going to learn the multi-dimensional array in C# programming.

 

The multi-dimensional array is known as a rectangular array. The simplest form of the multi-dimensional array is two-dimensional arrays. The two-dimensional array is a list of a one-dimensional array.


Let's declare a two-dimensional array in C#.

>int[ ,] arr=new[2,2]; 
In the above example , we declared two dimesional array in C# .
This is the two dimensional array declaration and initialiszation in C# . Let's declare three dimenstional array in C# .
 int [ , ,] arr=new int[2,3,2]; 

 

Two-dimensional array in C#.


C# supports a two-dimensional array. As we discussed above this the simplest form of a multidimensional array. The two-dimensional array has rows and columns. The rows are denoted by the x and columns are denoted by y.

Let's create an example of a two-dimensional array in C# programming.


Example of a two-dimensional array in C#.


In this example, we create 4 rows and 3 columns. 


using System;

namespace TwoDArrayApplication {

   class TwoDArray {
   
      static void Main(string[] args) {
         /*  4 rows and 3 columns*/
         int[,] arr = new int[4, 3] {{0,0,0}, {1,1,1}, {2,2,2}, {3,3,3} };
         int i, j;
         
         for (i = 0; i < 4; i++) {
            
            for (j = 0; j < 3; j++) {
               Console.WriteLine("arr[{0},{1}] = {2}", i, j, arr[i,j]);
            }
         }
         Console.ReadKey();
      }
   }
}


Output -

 
arr[0,0] = 0
arr[0,1] = 0
arr[0,2] = 0
arr[1,0] = 1
arr[1,1] = 1
arr[1,2] = 1
arr[2,0] = 2
arr[2,1] = 2
arr[2,2] = 2
arr[3,0] = 3
arr[3,1] = 3
arr[3,2] = 3

In the above example, we created 4 rows and 3 columns in the array. We used for loop to get each element value.

Let's create another example of two dimensional in C#. In this example of C#, we will create 3 rows and 2 columns.


using System;

namespace TwoDArrayApplication {

   public class TwoDArray {
   
      public static void Main(string[] args) {
         /*  3 rows and 2 columns*/
         int[,] arr = new int[3, 2] {{0,1}, {1,2},{2,3}};
         int i, j;
         
         for (i = 0; i < 3; i++) {
            
            for (j = 0; j < 2; j++) {
               Console.WriteLine("arr[{0},{1}] = {2}", i, j, arr[i,j]);
            }
         }
        
      }
   }
}

Output -

 
arr[0,0] = 0
arr[0,1] = 1
arr[1,0] = 1
arr[1,1] = 2
arr[2,0] = 2
arr[2,1] = 3

In this, way you can create the multidimensional array in C# programming.


Please Share

Recommended Posts:-