C# Jagged Array

The C# Jagged is an array whose elements are also an array, i.e., it is an array of arrays. These elements inside a jagged array can be of different dimensions and even can be of different sizes.

A Jagged array in C# can be declared and initialized as follows:

Int[][] JaggedAr = new int[2][];

Here size 2 represents the number of arrays, i.e., two in JaggedAr[][].

We have to initialize the arrays inside before using the C# Jagged.

JaggedAr[0] = new int[]{5,9,6};

JaggedAr[1] = new int[]{2,5};

Let us see an example code demonstrating Jagged arrays.

C# Jagged Array Example

The below-shown example explains to you the declaration and use of the Jagged Array.

using System;
 
 class program
 {
     public static void Main()
     {
         string[] NameOfEmployee = new string[2];
         NameOfEmployee[0] = "John";
         NameOfEmployee[1] = "Winson";
 

         string[][] JaggedAr = new string[2][];
         JaggedAr[0] = new string[] { "Bachelors", "masters", "Doctrate" };
         JaggedAr[1] = new string[] { "Bachelors", "Masters" };
         for(int i = 0;i<JaggedAr.Length;i++  )
         {
             Console.WriteLine(NameOfEmployee[i]);
             Console.WriteLine("-------");
             string[] arrayin = JaggedAr[i];
            
             for(int j = 0; j< arrayin.Length;j++)
             {
                 Console.WriteLine(arrayin[j]);
             }
             Console.WriteLine();
         }

         Console.ReadLine();
     }
 }
C# Jagged Array 1

ANALYSIS

NameOfEmployee[] is a string array in which there are two elements.

JaggedAr[][] is the C# jagged array having two string arrays.

JaggedAr[0] has three elements —— Bachelors, masters, and Doctorate.

JaggedAr[1] has two elements in it —– Bachelors, Masters.

Since JaggedAr.Length is 2, When i = 0, 0<2 condition returns true. So, the control enters the parent loop and prints NameOfEmployye[0], which is.

John
——

Now JaggedAr[0] is stored in arrayin[]

When j=0, j<arrayin.Length, i.e., 0<3 since JaggedAr[0] is having three elements.

0<3 returns true. So, C# prints Bachelors.

Again j++, i.e., 1

Now, 1 < 3 returns true. So, it prints Masters

Again j++, i.e., 2

Next, 2 < 3 returns true, and It prints Doctorate.

Again j++, i.e., 3

Now, 3 < 3 returns false come out of the child loop.

Now Console.WriteLine() is executed.

Again C# Jagged Array increments i in the parent loop. This time i=1, so 1<2 returns true. Thus enters the loop and prints NameOfEmployee[1], i.e.,

Winson
———-

arrayin = JaggedAr[1]

j=0 and j<arrayin.Length, which is 2, and it returns true. So, the control enters the child loop and prints arrayin[0]

Bachelors

j++ = 1 and 1<2 returns true. Enters the child loop and prints arrayin[1], i.e.,

Masters

j++ = 2 and 2<2 returns false. So, it comes out of the child loop and executes.

Console.WriteLine();

Now increments I by 1 so i++ = 2

2<2 returns false, so it comes out of the parent loop.

Categories C#