Jagged arrays is a one of built-in data structure in .Net framework where all the elements of the data structure are of same type. Though it seems simple, but it can easily become puzzling when mixed with other array structures. In this blog, I will try to solve this puzzle.
Lets start with a simple jagged array:
In above statement we declared an array, where each element of the array is itself an array of integers. As part of initialization, we declared the size of first array as 2. First element of this array is further initialized with array of size 3 (2,3,4) and second element is initialized with array of size 4 (5,6,7,8).
Lets make it complex:
Whats the outcome of above statement. Well there are two possibilities:
a) We are declaring a single dimension array where each element is itself a matrix of integers:
b) We are declaring a matrix where each element of matrix is itself an array of integers.
The correct answer is b. The above statement will create a matrix where each element is a array by itself. Following code snippet will combine the declaration and initialization of same structure.
In above code we declared a matrix of 2×2. Element at [0,0] is an array of size 1 (1). Element at [0,1] is an array of size 2 (2,3). Element at [1,0] is an array of size 3 with values (4,5,6) and last element [1,1] is an array of size 4 with values (7,8,9,10).
Lets make it more complex.
By following the same convention, it is matrix where each element of the matrix is a matrix of integers. Following code will declare and initialize matrix of matrix:
Here we declared a matrix of 2×2. Element at position [0,0] is a matrix of 1×2. Element at position [0,1] is a matrix of 2×2. Element at position [1,0] is a matrix of 1×2 whereas element at position [1,1] is a matrix of 1×1.
Though I will not recommend (as it becomes difficult to maintain and visualize), you can combine jagged arrays with more deeper level to achieve the desired data structure. As an example following code is declaring a matrix where each element is a matrix. Each element of sub matrix is a one dimensional array.