C# provides the ability to create a special type of two dimensional array called as Jagged Array. In simple terms, a jagged array is an array of arrays. A jagged array is a little different than a two dimensional array, the major difference being that in a jagged array the length of each array may differ. Thus, a jagged array can be used to create a table in which the lengths of the rows are not the same.
Declaring a jagged array:
|
1 |
data_type [][] array_name = new data_type[size][]; |
Example:
|
1 |
int [][] jagged = new int[4][]; |
After the jagged array has been declared, we have to initialize individual array of the jagged array.
Initializing the jagged array:
|
1 2 3 |
jagged[0] = new int[3]; jagged[1] = new int[6]; jagged[2] = new int[2]; |
and so on..
You can also use a for loop to initialize the jagged array.
Assigning values to the jagged array:
Once we have initialized the jagged array, we can now store values in the jagged array. Values can be stored by using the two indexes along with the jagged array name.
Example:
|
1 2 |
jagged[0][1] = 10; jagged[1][2] = 5; |
Just like in declaration, you could also use a for loop to store values in a jagged array.
Example:
|
1 2 3 |
for(int i = 0; i<jagged[0].Length; i++){ jagged[0][i] = int.Parse(Console.ReadLine()); } |
Vlad
Latest posts by Vlad (see all)
- Code jam “Tic-Tac-Toe-Tomek” solution in java - April 19, 2013
- Code jam “Minimum Scalar product” solution in java - March 18, 2013
- Code jam Store Credit solution in java - March 10, 2013