Understanding Jagged Arrays in C# with Examples

Introduction

Programming languages like C# and Java frequently use jagged arrays, a sort of multidimensional array where each element is also an array. Jagged arrays allow the inner arrays to have varying lengths, in contrast to ordinary multidimensional arrays, like a 2D or 3D array, where all the inner arrays have the same length. Because of this, jagged arrays can be used to represent a variety of non-rectangular, irregular data structures.
Here is a thorough explanation and a C# sample to show how jagged arrays work.

What is Jagged Arrays in C#?

Jagged arrays in C# are arrays of arrays. The outer array's elements are arrays in and of themselves. These inner arrays can be of various lengths, offering a versatile approach to organizing and managing data.
Here is a description of jagged arrays in C#, along with an example of code.

Declaration and Initialization

To declare and initialize a jagged array, you use the following syntax.

data_type[][] jaggedArrayName = new data_type[num_of_arrays][];
  • data_type: The kind of data that will be stored in the inner arrays, such as an int, a string, or a special class type.
  • jaggedArrayName: The name you give the jagged array is called jaggedArrayName. In the below example, I have taken studentdata as jaggedArrayName.
  • num_of_arrays: There are num_of_arrays inner arrays in the outer array. The inner arrays' widths can also be left off during startup, giving you the option to change them individually later.

Here I am taking an example where we need to create a C# program, for instance, that uses a jagged array to store and show information about students and their test results.

using System;

class Program
{
    static void Main()
    {
        // Declare and initialize a jagged array to store student names and their exam scores
        string[][] studentData = new string[3][];

        // Initialize the inner arrays with different sizes
        studentData[0] = new string[] { "Mukesh", "90", "85" };
        studentData[1] = new string[] { "Mahesh", "88", "92", "78" };
        studentData[2] = new string[] { "Manish", "75", "80", "95", "88" };

        // Display the student data
        for (int i = 0; i < studentData.Length; i++)
        {
            Console.Write(studentData[i][0] + ": ");
            for (int j = 1; j < studentData[i].Length; j++)
            {
                Console.Write(studentData[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}

Output

Output

Please feel free to drop a comment if you have any doubts or queries related to the above explanation.

Thanks, Mukesh


Similar Articles