Here I
would like to explain
Jagged Array :
The elements of a jagged array can be of different sizes and dimensions . A jagged array can be also called as "array of arrays."
It doesn't allocate memory while declaring an array.
How to Declare a Jagged Array :
we can declare the
jagged array as
int[][] jaggedArray = new int[5][];
Here int[5][] specifies number of rows are 5 fixed.
Following specifies number of columns for reach row. here
Declaring Column sizes for each
Row in Jagged array:
jaggedArray[0] = new int[3]; first row
contains 3 integer values
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
jaggedArray[3] = new int[8];
jaggedArray[4] = new int[10];
you can not create a row of different type other than the
declaring type. here you can create a
size of integer type only, you can not create int to string
jaggedArray[1] = new string[5];//Error
We can initialize Jagged arrays in Three ways
First Way:
jaggedArray[0] = new int[] { 3, 5, 7,
};
jaggedArray[1] = new int[] { 1, 0, 2,
4};
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 };
Second Way:
int[][] jaggedArray = new int[][]
{
new int[] { 3, 5, 7, },
new int[] { 1, 0, 2, 4 },
new int[] { 1, 6 },
new int[] { 1, 0, 2, 4, 6, 45, 67, 78 }
};
Third Way:
int[][] jaggedArray =
{
new int[] { 3, 5, 7, },
new int[] { 1, 0, 2, 4 },
new int[] {1, 2, 3, 4, 5, 6, 7, 8},
new int[] {4, 5, 6, 7, 8}
};
Example Program :
No comments:
Post a Comment