In addition to the single-dimension arrays you have seen thus far, C# also supports two varieties of multidimensional arrays. The first of these is termed a rectangular array, which is simply an array of multiple dimensions, where each row is of the same length. To declare and fill a multidimensional rectangular array, proceed as follows:
static void Main(string[] args)
{
...
// A rectangular MD array.
int[,] myMatrix;
myMatrix = new int[6,6];
// Populate (6 * 6) array.
for(int i = 0; i < 6; i++)
for(int j = 0; j < 6; j++)
myMatrix[i, j] = i * j;
// Print (6 * 6) array.
for(int i = 0; i < 6; i++)
{
for(int j = 0; j < 6; j++)
Console.Write(myMatrix[i, j] + "\t");
Console.WriteLine();
}
...
}
Figure shows the output (note the rectangular nature of the array).
The second type of multidimensional array is termed a jagged array. As the name implies, jagged arrays contain some number of inner arrays, each of which may have a unique upper limit, for example:
static void Main(string[] args)
{
...
// A jagged MD array (i.e., an array of arrays).
// Here we have an array of 5 different arrays.
int[][] myJagArray = new int[5][];
// Create the jagged array.
for (int i = 0; i < myJagArray.Length; i++)
myJagArray[i] = new int[i + 7];
// Print each row (remember, each element is defaulted to zero!)
for(int i = 0; i < 5; i++)
{
Console.Write("Length of row {0} is {1} :\t", i, myJagArray[i].Length);
for(int j = 0; j < myJagArray[i].Length; j++)
Console.Write(myJagArray[i][j] + " ");
Console.WriteLine();
}
}
Figure shows the output (note the jaggedness of the array).
Now that you understand how to build and populate C# arrays, let’s turn our attention to the ultimate base class of any array: System.Array.
No comments:
Write comments