Jagged Array In C#

In C#, the jagged array is also known as an "array of arrays", where each element in the main array is itself an array. The length of each element inside the jagged array can be different. Jagged arrays store the arrays instead of literal values. Unlike multidimensional arrays, jagged arrays enable the inner array to be of differing lengths, which gives more flexibility in storing elements. It makes them more efficient when working with uneven data structures.

Simple Example:

Let us take a simple example of a jagged array in C# , which declares, initializes, and traverses jagged arrays.

Example

Example

using System;

public class JaggedArrayTest  

{  

    public static void Main()  

    {  

        int[][] arr = new int[2][];// Declare the array  

  

        arr[0] = new int[] { 15, 25, 38, 45 };// Initialize the array          

       arr[1] = new int[] { 75, 28, 19, 41, 35, 39 };  

  

        // Traverse array elements  

        for (int i = 0; i < arr.Length; i++)  

        {  

            for (int j = 0; j < arr[i].Length; j++)  

            {  

                System.Console.Write(arr[i][j]+" ");  

            }  

            System.Console.WriteLine();  

        }  

    }  

}

Output:

Output

15 25 38 45 

75 28 19 41 35 39

Here, we will discuss the declaration, initialization, and accessing elements of jagged arrays in C#.

Declaration of Jagged Array:

In a C# jagged array, we only need to specify the number of rows, not column numbers. If we define the number of columns in the jagged array, the array loses its jagged feature and becomes a multidimensional array. It is declared with two square brackets , which indicates that it is an array of arrays.

Here, the first square bracket refers to the size of the main array. On the other side, the second bracket does not specify the array dimensions, but instead, it indicates that each element in the main array is another array, which can have different lengths.

Syntax:

It has the following syntax:

Example

Data-type[][] name_of_array = new data-type[rows][];

Let us illustrate the declaration of the jagged array with an example:

Example

//declare the jagged array

int[][] arr = new int[2][];  

In this example,
  • int: It defines the data type of the array.
  • : Square brackets represent the jagged array.
  • arr: It represents the name of the jagged array.
  • 2: It defines the number of arrays inside the jagged array.
  • Initialization of Jagged Array:

We can individually assign the size of elements because every member of a jagged array is itself an array. Let us take an example to initialize a jagged array in C#.

Example

//set the size of the first array as 4

arr[0] = new int[4];  

//set the size of the first array as 4

arr[1] = new int[6];

Initialization and filling elements in the jagged array

In C#, there are several methods to initialize the array in the jagged array. Some of them are as follows:

1. Using the Index Number:

Once the jagged array is initialized in C#, we may utilize the index number to initialize it. It enables us to dynamically initialize values for each element in the array by accessing its specific index position.

Example:

Let us consider an example to illustrate how we can initialize the jagged array using the Index number in C#.

Example

Example

// Declare a jagged array with 2 rows

int[][] jagged_array = new int[2][];



// Initialize each row with a specific size

jagged_array[0] = new int[3]; // Initialize first row with 3 elements

jagged_array[1] = new int[2]; // Initialize second row with 2 elements



// Initialize the first array

jagged_array[0][0] = 4;

jagged_array[0][1] = 3;

jagged_array[0][2] = 7;



// Initialize the second array

jagged_array[1][0] = 2;

jagged_array[1][1] = 5;

Where,

  • The index at the first bracket specifies the index of the row in the jagged array.
  • The index at the second bracket specifies the index of the element inside that specific row of the jagged array.
  • 2. Initialize without defining the size of array elements:

When the jagged array's size is not predetermined, we may directly initialize its elements using the inline initialization with specific values.

Example:

Let us consider an example to illustrate how we can initialize the jagged array without using the size of the array in C#.

Example

Example

// declaring an integer jagged array

int[][] arr = new int[2][];



// initializing each row with values

arr[0] = new int[4] { 11, 21, 56, 78  }; // First row

arr[1] = new int[6] { 42, 61, 37, 41, 59, 63 };     // Second row

3. Initialize while declaring Jagged Array:

In C# programming, we may directly utilize array initializers to initialize a jagged array at the time of declaration. It allows us to declare and populate the array in a single step, which makes the code more concise and expressive.

Example:

Let us consider an example to illustrate how to initialize the array while declaring a jagged array in C#.

Example

Example

int[][] jagged_array = {

    new int[] {17, 24, 31, 42 }  // First row (4 elements)

    new int[] {18, 27, 16};  // Second row (3 elements)

    new int[] {22, 15};  // Third row (2 elements)

};

Example 1: A program to implement the jagged array in C#.

Example

Example

using System; // Importing the System namespace



public class C# Tutorial 

{

    public static void Main()

    {

        int[][] jaggedArr = new int[4][]; // Array Declaration  

          // Array Initialization

        jaggedArr[0] = new int[] { 4, 2, 5, 9 }; // First row with 4 elements

        jaggedArr[1] = new int[] { 8, 1, 7 }; // second row with 3 elements

        jaggedArr[2] = new int[] { 6, 3, 2, 5 }; // third row with 4 elements

        jaggedArr[3] = new int[] { 9, 4, 8, 1, 6 }; // fourth row with 5 elements



          // Iterating the elements

        for (int i = 0; i < jaggedArr.Length; i++) 

        {

            Console.Write("Row " + i + ": "); // Printing row index

             foreach (int num in jaggedArr[i]) 

                Console.Write(num + " "); // Printing elements of the row

          

            Console.WriteLine(); // Moving to the next line after printing a row

        }

    }

}

Output:

Output

Row 0: 4 2 5 9 

Row 1: 8 1 7 

Row 2: 6 3 2 5 

Row 3: 9 4 8 1 6

Explanation:

In this example, we have taken a public class named C# Tutorial. After that, a jaggedArr function is declared as a jagged array with 4 elements, and each can hold an array of integers. At this point, the inner arrays are not initialized. Every element of the given jagged array is initialized as an array of integers.

After that, the outer loop iterates over each row of the jagged array. The inner foreach loop iterates over every element in the current row, which prints the element that is separated by spaces. At the end, the console.WriteLine function moves the cursor to the next line after printing all the elements of the current row, which ensures that each row is displayed on a separate line.

Example 2: Jagged Array upon declaration

Let us take a simple example of the jagged array, which initializes the jagged arrays upon declaration in C#.

Example

Example

using System;

public class JaggedArrayTest  

{  

    public static void Main()  

    {  

        // Declare and initialize a jagged array with 4 rows

        int[][] arr = new int[4][]{  

        new int[] { 25, 45, 41, 78, 34 },  

        new int[] { 4, 52, 36, 15, 27, 73 },  

        new int[] { 2, 5, 28, 31, 47  },

        new int[] { 13, 53, 72  }

        }; 

  

        // Iterate through each row of the jagged array  

        for (int i = 0; i < arr.Length; i++)  

        {  

            // Iterate through each element in the current row

            for (int j = 0; j < arr[i].Length; j++)  

            {  

                // Print the current element followed by a space

                System.Console.Write(arr[i][j]+" ");  

            }  

            System.Console.WriteLine();  

        }  

    }  

}

Output:

Output

25 45 41 78 34 

4 52 36 15 27 73 

2 5 28 31 47 

13 53 72

Explanation:

In this example, we have taken a JaggedArrayTest class. After that, we declare a jagged array with 4 elements upon declaration, and each of them can handle an array of integers. After that, the outer loop iterates over each row of the jagged array.

The inner foreach loop iterates over every element in the current row, which prints the element that is separated by spaces. At the end, the console.WriteLine function moves the cursor to the next line after printing all the elements of the current row, which ensures that each row is displayed on a separate line.

Accessing and Modifying the Elements of a Jagged Array:

In C#, we can access the jagged array elements using the two indices. The first indices refer to the outer array (row), and the second indices refer to the inner array(column).

Example

//Accessing the first elements of a jagged array of a second row

int element = jaggedArray[1][0];

On the other hand, we can modify the element of a jagged array by allocating a new value using their indices.

Example

// Modify the second element of the first row to 15

jaggedArr[0][1] = 15;

Example:

Let us take an example to illustrate how to access and modify the elements in C#.

Example

Example

using System;

public class C# Tutorial  

{

    static void Main(string[] args)

    {

        // Here is the declaration of a jagged array with 3 rows

        int[][] arr = new int[3][];

        

        // Here is the initialization of each row of the jagged array   

        arr[0] = new int[] { 5, 7, 8, 4}; // First row

        arr[1] = new int[] { 3, 9, 12 };  // Second row

        arr[2] = new int[] { 17, 19, 45, 16 };  // Third row



        // Accessing the third element in the second row

        int value = arr[1][2];  

        // Here, we are modifying the third element in

          // the second row (from 12 to 15)

        arr[1][2] = 15;     

                Console.WriteLine("Accessed Value: " + value); // Print the accessed value 

        Console.WriteLine("Modified Value: " + arr[1][2]);  // Print the modified value 

    }

}

Output:

Output

Accessed Value: 12

Modified Value: 15

Explanation:

In this example, we have taken a class named C# Tutorial. Here, we declare a jagged array named arr that contain 3 rows. Every element of an arr function is an array that can have a different length. Every row of the jagged array is initialized with a specific value.

After that, we access the third element in the second row that contains the value 12, and then we update the previously accessed element from 12 to 15. At the end, it prints the output in the console.

Jagged Arrays with Multidimensional Arrays

In C#, we can also utilize the jagged arrays in multi-dimensional arrays to create complex data structures. In order to iterate a jagged array, we may utilize the nested loops. The outer loop iterates via the rows, and the inner loop iterates via the elements in every row.

Syntax:

It has the following syntax:

Example

//initializing 4 2-Dimensional array elements in 1-Dimensional array

int[][, ] jagged_array = new int[4][, ] 

{

    new int[, ] { {3, 4}, {2, 7}, {5, 8} },

    new int[, ] { {18, 12}, {19, 22}, {35, 55} },

    new int[, ] { {23, 54}, {26, 84}, {67, 37}, {49, 73} },

    new int[, ] { {81, 32}, {5, 7}, {45, 94} },

};

Example:

Let us take an example to demonstrate the iteration of the jagged array in a multidimensional array in C#.

Example

Example

using System;

public class MultiJaggedArray

{

    public static void Main()

    {

        // Declare and initialize a jagged array where each element is a two-dimensional array

        int[][,] jag_array = new int[4][,]

        {

            // First 2D array with 3 rows and 2 columns

            new int[,] { {3, 4}, {2, 7}, {5, 8} },

            // Second 2D array 

            new int[,] { {18, 12}, {19, 22}, {35, 55} },

            // Third 2D array with 4 rows and 2 columns

            new int[,] { {23, 54}, {26, 84}, {67, 37}, {49, 73} },

            // Fourth 2D array

            new int[,] { {81, 32}, {5, 7}, {45, 94} },

        };



        // Iterate through each 2D array in the jagged array

        for (int i = 0; i < jag_array.Length; i++)

        {

            Console.WriteLine($"Elements of the Jagged Array {i+1}:");

            // GetLength method takes an integer that indicates the array's dimension.

            for (int j = 0; j < jag_array[i].GetLength(0); j++)

            {

                for (int k = 0; k < jag_array[i].GetLength(1); k++)

                {

            // Print the element at position [j, k] in the current 2D array

                    Console.Write("{0} ",jag_array[i][j, k]);

                }

                Console.WriteLine();

            }

            Console.WriteLine();

        }  

    }  

}

Output:

Output

Elements of the Jagged Array 1:

3 4 

2 7 

5 8 

Elements of the Jagged Array 2:

18 12 

19 22 

35 55 

Elements of the Jagged Array 3:

23 54 

26 84 

67 37 

49 73 

Elements of the Jagged Array 4:

81 32 

5 7 

45 94

Explanation:

In this example, we have taken a MultiJaggedArray class. After that, we declare a jagged array that contains 4 elements and each element is a two-dimensional array. Every element of the jagged array is initialized with a two-dimensional array that has different sizes.

For every 2D array, it retrieves the number of rows and columns using GetLength(0) and GetLength(1). After that, it iterates via each row and column to access and print the element.

C# Jagged Arrays MCQs

  1. How can we declare an integers jagged array with 3 rows in C#?
  • int jaggedArray = new int2;
  • int[,] jaggedArray = new int[2, ];
  • int jaggedArray = new int[2];
  • int jaggedArray = new int[2];
  1. What will be the output of the following code?
  2. Example
    
    int[][] jaggedArray = new int[2][];
    
    jaggedArray[0] = new int[] {2, 15, 27};
    
    jaggedArray[1] = new int[] {10, 24};
    
    Console.WriteLine(jaggedArray[1][1]);
    
  1. What is the default value of an uninitialized element in a jagged array of integers in C#?
  • Null
  • Undefined
  1. How do we initialize a jagged array with different row lengths in C#?
  • By using a multidimensional array.
  • It is not possible to have row of different lengths.
  • By declaring a single dimensional array.
  • By specifying the length of every row individually.
  1. What is the following option is true about the jagged arrays?
  • Jagged arrays are an array of arrays that allow every inner array to have different lengths.
  • Jagged arrays are known as single-dimensional arrays.
  • Jagged arrays are multidimensional arrays with fixed row sizes.
  • Jagged arrays cannot contain arrays as elements.

Input Required

This code uses input(). Please provide values below: