How to initialize a rectangular array in C#?

CsharpProgrammingServer Side Programming

An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contiguous memory locations.

Multi-dimensional arrays are also called rectangular array. Multidimensional arrays are initialized by specifying bracketed values for each row.

The following array is with 2 rows and each row has 2 columns.

int [,] a = new int [2,2] {
{20, 50} , /* initializers for row indexed by 0 */
{15, 45} , /* initializers for row indexed by 1 */
};

Let us see an example −

Example

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         /* an array with 2 rows and 2 columns*/
         int [,] a = new int [2,2] {
            {20, 50} , /* initializers for row indexed by 0 */
            {15, 45} , /* initializers for row indexed by 1 */
         };
         int i, j;

         for (i = 0; i < 2; i++) {
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
            }
         }  
         Console.ReadKey();
      }
   }
}
raja
Published on 31-Aug-2018 08:34:05
Advertisements