How to use jagged arrays in C#

By FoxLearn 1/4/2025 4:46:14 AM   89
Jagged arrays are a type of multi-dimensional array that allows each row to have varying lengths, which can improve performance when working with arrays.

They consist of arrays within arrays, with each inner array possibly having a different size. While arrays are typically used to store elements of the same data type in contiguous memory locations, jagged arrays provide more flexibility by enabling each row to have a different size. Jagged arrays can be implemented in any programming language that supports arrays, and they are useful for optimizing performance in situations involving multi-dimensional data.

Getting Started with Jagged Arrays in C#

In this section, we'll dive into how to declare, initialize, and access jagged arrays in C#.

A jagged array is an array of arrays, where each inner array can have a different size. This makes jagged arrays more flexible compared to regular multi-dimensional arrays. In a jagged array, the number of rows is fixed, but the number of columns can be varied, which allows you to allocate memory dynamically at runtime.

Let's start by declaring a jagged array of strings:

string[][] str = new string[3][];

This line creates an array with 3 rows, and each row can store an array of strings with varying lengths. Now, let's initialize each row with a different number of string elements:

str[0] = new string[2];
str[1] = new string[4];
str[2] = new string[3];

We can now store strings in each of the inner arrays:

str[0][0] = "Apple";
str[0][1] = "Banana";

str[1][0] = "Carrot";
str[1][1] = "Potato";
str[1][2] = "Cucumber";
str[1][3] = "Tomato";

str[2][0] = "Orange";
str[2][1] = "Grape";
str[2][2] = "Lemon";

Here's the full code that declares, stores, and displays the data in the jagged array:

public static void Main(string[] args)
{
    // Declare the jagged array
    string[][] str = new string[3][];
    str[0] = new string[2];
    str[1] = new string[4];
    str[2] = new string[3];

    // Store data in the jagged array
    str[0][0] = "Apple";
    str[0][1] = "Banana";

    str[1][0] = "Carrot";
    str[1][1] = "Potato";
    str[1][2] = "Cucumber";
    str[1][3] = "Tomato";

    str[2][0] = "Orange";
    str[2][1] = "Grape";
    str[2][2] = "Lemon";

    // Display the content of each string array inside the jagged array
    for (int i = 0; i < 3; i++)
    {
        Console.WriteLine("Row " + (i + 1) + ":");
        for (int j = 0; j < str[i].Length; j++)
        {
            Console.WriteLine(str[i][j]);
        }
    }

    Console.Read();
}

In this program, the number of rows is fixed at 3, but the number of columns varies across the rows. The use of a jagged array ensures that we only allocate the exact memory needed for each row, making the program memory efficient.

Jagged arrays can be used with any data type. Let's now create a jagged array of double values. Here’s how we can declare and initialize a jagged array that stores double values of varying sizes:

double[][] temperatureReadings = new double[4][];

We can then assign different lengths to each row based on the number of readings:

temperatureReadings[0] = new double[7];  // Week 1, 7 days
temperatureReadings[1] = new double[5];  // Week 2, 5 days
temperatureReadings[2] = new double[6];  // Week 3, 6 days
temperatureReadings[3] = new double[7];  // Week 4, 7 days

The complete code to print these readings:

public static void Main(string[] args)
{
    // Declare the jagged array for temperature readings
    double[][] temperatureReadings = new double[4][];
    temperatureReadings[0] = new double[7];
    temperatureReadings[1] = new double[5];
    temperatureReadings[2] = new double[6];
    temperatureReadings[3] = new double[7];

    // Assign sample temperature data
    // Week 1
    temperatureReadings[0][0] = 20.5;
    temperatureReadings[0][1] = 21.3;
    temperatureReadings[0][2] = 22.1;
    temperatureReadings[0][3] = 19.8;
    temperatureReadings[0][4] = 18.7;
    temperatureReadings[0][5] = 23.4;
    temperatureReadings[0][6] = 22.0;

    // Week 2
    temperatureReadings[1][0] = 19.0;
    temperatureReadings[1][1] = 20.2;
    temperatureReadings[1][2] = 21.8;
    temperatureReadings[1][3] = 22.3;
    temperatureReadings[1][4] = 19.5;

    // Week 3
    temperatureReadings[2][0] = 17.8;
    temperatureReadings[2][1] = 19.0;
    temperatureReadings[2][2] = 20.3;
    temperatureReadings[2][3] = 18.9;
    temperatureReadings[2][4] = 22.5;
    temperatureReadings[2][5] = 21.0;

    // Week 4
    temperatureReadings[3][0] = 23.3;
    temperatureReadings[3][1] = 24.0;
    temperatureReadings[3][2] = 21.9;
    temperatureReadings[3][3] = 22.8;
    temperatureReadings[3][4] = 19.6;
    temperatureReadings[3][5] = 20.5;
    temperatureReadings[3][6] = 21.2;

    // Display the temperature readings for each week
    for (int i = 0; i < 4; i++)
    {
        Console.WriteLine("Week " + (i + 1) + " temperatures:");
        for (int j = 0; j < temperatureReadings[i].Length; j++)
        {
            Console.WriteLine($"Day {j + 1}: {temperatureReadings[i][j]}°C");
        }
        Console.WriteLine();
    }

    Console.Read();
}

In this example, we use a jagged array to store daily temperature readings for four weeks, with varying numbers of days for each week. By only allocating memory for the actual number of days per week, we save memory compared to using a regular multi-dimensional array.

Jagged arrays are a useful feature in C# that allow you to create arrays with varying sizes in each dimension, making them both flexible and memory-efficient.