Jagged Array in C# with Example

Hi Programmers, welcome to new article of c#.net. This article i’ll write definition and program for jagged array in c# console application. The Jagged Array is an “array of an arrays”. It can store arrays in which length of each array
index can differ. For Example int[][] arr = new int[3][]; Here jagged array initialize with two brackets. First bracket for size and next bracket for dimension. let’s see the codes.

Example 1
Example 2

Directly Test Below codes into editor.

#Jagged Array with size three.
using System;
namespace ConsoleApp1 {
    class Program {       
        static void Main(string[] args)
        {
            int[][] arr = new int[3][];

            arr[0] = new int[3];
            arr[1] = new int[1];
            arr[2] = new int[2];

            arr[0][0] = 23;
            arr[0][1] = 67;
            arr[0][2] = 85;

            arr[1][0] = 100;

            arr[2][0] = 200;
            arr[2][1] = 300;

            for(int i = 0;i<arr.Length;i++)
            {
                int[] x = arr[i];
                for(int j=0;j<x.Length;j++)
                {
                    Console.WriteLine(x[j]);
                }
            }
        }       
    }
}

********************
#Jagged Array with size five

using System;
namespace ConsoleApp1 {
    class Program {       
        static void Main(string[] args){
            int[][] arr = new int[5][];

            arr[0] = new int[3];
            arr[1] = new int[5];
            arr[2] = new int[2];
            arr[3] = new int[4];
            arr[4] = new int[7];
            
            arr[0] = new int[] { 2, 5, 8 };
            arr[1] = new int[] { 2, 4, 6, 8, 10 };
            arr[2] = new int[] { 11, 66 };
            arr[3] = new int[] { 6, 8, 10 };
            arr[4] = new int[] { 11, 66,88,99 };

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

Happy Coding…Thanks.

Post Author: adama