C Sharp Jagged Arrays

C# Jagged Arrays

The elements of a jagged array in C# are arrays, and hence it is also called “array of arrays”. In a jagged array, the size of the elements can be different.

Declaration of Jagged array:

In the below example, we are declaring a jagged array with two elements.

int[][] a = new int[5][];

Initialization of Jagged array:

In the below example, we are initializing a jagged array with different size of the elements.

a[0] = new int[5];
a[1] = new int[10];

Initialization and filling elements in Jagged array:

In the below example, we are initializing and filling elements in a jagged array.

Example:

a[0] = new int[5] { 1, 2, 3, 4, 5 };
a[1] = new int[10] { 1, 2, 3, 4, 5 , 6, 7, 8, 9, 10 };

It is optional to specify the size of elements in the jagged array.

Example:

a[0] = new int[] { 1, 2, 3, 4, 5 };
a[1] = new int[] { 1, 2, 3, 4, 5 , 6, 7, 8, 9, 10 };

Example:

public class Example  
{  
    public static void Main()  
    {  
        int[][] a = new int[2][]; // Declare the array  
 
        a[0] = new int[] { 1, 2, 3, 4, 5 }; // Initialize the array          
        a[1] = new int[] { 10, 20, 30, 40, 50, 60 };  
 
        // Traverse array elements  
        for (int i = 0; i < a.Length; i++)  
        {  
            for (int j = 0; j < a[i].Length; j++)  
            {  
                System.Console.Write(a[i][j]+" ");  
            }  
            System.Console.WriteLine();  
        }  
    }  
}

Output:

Explanation:

In the above example, we are declaring, initializing and traversing a jagged array upon declaration.

Initialization of Jagged array upon Declaration:

public class Example  
{  
    public static void Main()  
    {  
        int[][] a = new int[4][]{  
        new int[] { 1, 2, 3, 4, 5 },  
        new int[] { 10, 20, 30, 40, 50, 60 },  
        new int[] { 100, 200, 300, 400, 500, 600, 700 },
        new int[] { 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000 }
        };  
 
        // Traverse array elements  
        for (int i = 0; i < a.Length; i++)  
        {  
            for (int j = 0; j < a[i].Length; j++)  
            {  
                System.Console.Write(a[i][j]+" ");  
            }  
            System.Console.WriteLine();  
        }  
    }  
}

Output:

Explanation:

In the above example, we are initializing a jagged array upon declaration.

Please Share