Arrays of Arrays (Jagged Arrays)

Multidimensional arrays, as discussed in the last section, are said to be rectangular because each ” row ” is the same size. Using the last example, you can have a y coordinate of 0 to 3 for any of the possible x coordinates.
 
It is also possible to have jagged arrays, whereby “ rows ” may be different sizes. For this, you need an array in which each element is another array. You could also have arrays of arrays of arrays if you want, or even more complex situations. However, all this is only possible if the arrays have the same base type.
 
The syntax for declaring arrays of arrays involves specifying multiple sets of square brackets in the declaration of the array, as shown here:

int[][] jaggedIntArray;

Unfortunately, initializing arrays such as this isn ’ t as simple as initializing multidimensional arrays. You can ’ t, for example, follow the preceding declaration with this:

jaggedIntArray = new int[3][4];

Even if you could do this, it wouldn ’ t be that useful because you can achieve the same effect with simple multidimensional arrays with less effort. Nor can you use code such as this:

jaggedIntArray = {{1, 2, 3}, {1}, {1, 2}};

You have two options. You can initialize the array that contains other arrays (I ’ ll call these sub – arrays for clarity) and then initialize the subarrays in turn:

jaggedIntArray = new int[2][];
jaggedIntArray[0] = new int[3];
jaggedIntArray[1] = new int[4];

Example(jagged arrays)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[][] divisors1To10 = {new int[] {1},
                                        new int[] {1, 2},
                                        new int[] {1, 3},
                                        new int[] {1, 2, 4},
                                        new int[] {1, 5},
                                        new int[] {1, 2, 3, 6},
                                        new int[] {1, 7},
                                        new int[] {1, 2, 4, 8},
                                        new int[] {1, 3, 9},
                                        new int[] {1, 2, 5, 10}};

            foreach (int[] divisorsOfInt in divisors1To10)
            {
                foreach (int divisor in divisorsOfInt)
                {
                    Console.Write(divisor);
                }
                Console.WriteLine();
            }
            Console.ReadLine();
        }
    }
}