dataType [] [] arrayName = new dataType[no. of rows] []
int [] [] jaggedArray = new int[6] []
While declaration, the rows of jagged arrays are fixed in size, as shown above.
Once the array is declared, it needs to be initialized as follows:
int[][] jaggedArray = new int [4][] //array declaration
jaggedArray[0] = new int[2];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[6];
jaggedArray[3] = new int[8]; //size of each element array defined
jaggedArray[0] = new int[] { 3, 5};// population of jagged array
jaggedArray[1] = new int[] { 1, 2, 3, 4 };
jaggedArray[2] = new int[] { 5, 6, 7, 8, 9, 10 };
jaggedArray[3] = new int[] { 11, 12, 13, 14, 15, 16, 67, 24 };
The array can also be initialized and declared at the same time as follows:
int[][] jaggedArray = new int[][]
{
new int[] { 3, 4, 5 },
new int[] { 1, 2, 4, 8, 16 },
new int[] { 1, 6 },
new int[] { 100, 20, 29, 45, 63, 45, 67, 78 }
};
Following is the code for declaring, initializing, and printing the contents of the jagged array.
using System;namespace jagged_array{class Program{static void Main(string[] args){int [][] jaggedArr = new int[3][]; //array declarationjaggedArr[0] = new int[2] {2, 4}; //jagged array initialization and populationjaggedArr[1] = new int[4] {45, 25, 23, 65};jaggedArr[2] = new int[3] {23, 67, 52};for(int i = 0; i < jaggedArr.Length; i++) // outer for loop to traverse through each elemment of array{System.Console.Write("Element({0})", i + 1);for(int j = 0; j< jaggedArr[i].Length; j++) // inner for loop to ouput the contents of jagged array{System.Console.Write(jaggedArr[i][j] + "\t"); // printing results of jagged array}System.Console.WriteLine();}}}}
for
loop to get the elements of the main array.for
loop to get the array within the array.Free Resources