A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays."
A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can differ.
Example:
A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can differ.
Example:
- int[][] jagArray = new int[5][];
Declaring and initializing jagged array.
- int[][] jaggedArray = new int[5][];
- jaggedArray[0] = new int[3];
- jaggedArray[1] = new int[5];
- jaggedArray[2] = new int[2];
- jaggedArray[3] = new int[8];
- jaggedArray[4] = new int[10];
- jaggedArray[0] = new int[] { 3, 5, 7, };
- jaggedArray[1] = new int[] { 1, 0, 2, 4, 6 };
- jaggedArray[2] = new int[] { 1, 6 };
- jaggedArray[3] = new int[] { 1, 0, 2, 4, 6, 45, 67, 78 };
- jaggedArray[4] = new int[] { 1, 0, 2, 4, 6, 34, 54, 67, 87, 78 };
A jagged array is an array of an array. Jagged arrays store arrays instead of any other data type value directly.
A jagged array is initialized with two square brackets [][]. The first bracket specifies the size of an array and the second bracket specifies the dimension of the array which is going to be stored as values. (Remember, jagged array always store an array.)
The following jagged array stores a two single dimensional array as a value:
Example: Jagged Array
int[][] intJaggedArray = new int[2][];
intJaggedArray[0] = new int[3]{1,2,3};
intJaggedArray[1] = new int[2]{4,5};
Console.WriteLine(intJaggedArray[0][0]); // 1
Console.WriteLine(intJaggedArray[0][2]); // 3
Console.WriteLine(intJaggedArray[1][1]); // 5
The following jagged array stores a multi-dimensional array as a value. Second bracket [,] indicates multi-dimension.
Example: Jagged Array
int[][,] intJaggedArray = new int[3][,];
intJaggedArray[0] = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
intJaggedArray[1] = new int[2, 2] { { 3, 4 }, { 5, 6 } };
intJaggedArray[2] = new int[2, 2];
Console.WriteLine(intJaggedArray[0][1,1]); // 4
Console.WriteLine(intJaggedArray[1][1,0]); // 5
Console.WriteLine(intJaggedArray[1][1,1]); // 6
Note :Be careful while working with jagged arrays. It will throw an IndexOutOfRange exception if the index does not exist.
No comments:
Post a Comment