Initializing rectangular and jagged arrays. - CSharp Language Basics

CSharp examples for Language Basics:Array

Description

Initializing rectangular and jagged arrays.

Demo Code

using System;/* ww  w. ja  v a2s  .  co m*/
class InitArray
{
   static void Main()
   {
      // with rectangular arrays, every row must be the same length.
      int[,] rectangular = {{1, 2, 3}, {4, 5, 6}};
      // with jagged arrays, we need to use "new int[]" for every row,
      // but every row does not need to be the same length.
      int[][] jagged = {new int[] {1, 2},
      new int[] {3},
      new int[] {4, 5, 6}};
      OutputArray(rectangular); // displays array rectangular by row
      Console.WriteLine(); // output a blank line
      OutputArray(jagged); // displays array jagged by row
   }
   static void OutputArray(int[,] array)
   {
      for (var row = 0; row < array.GetLength(0); ++row)
      {
         for (var column = 0; column < array.GetLength(1); ++column)
         {
            Console.Write($"{array[row, column]}  ");
         }
         Console.WriteLine(); // start new line of output
      }
   }
   static void OutputArray(int[][] array)
   {
      foreach (var row in array)
      {
         foreach (var element in row)
         {
            Console.Write($"{element}  ");
         }
         Console.WriteLine(); // start new line of output
      }
   }
}

Result


Related Tutorials