The examples on the previous page all refer to arrays with a single dimension. Consider the following representation of a one-dimensonal array,
Element | Student |
0 | Pinky |
1 | Perky |
2 | Bob |
3 | Agnes |
4 | Bill |
5 | McJack |
6 | Jimbob |
7 | Gladys |
Element | Exam Mark |
0 | 37 |
1 | 52 |
2 | 41 |
3 | 74 |
4 | 61 |
5 | 87 |
6 | 53 |
7 | 29 |
What we have now is two arrays in parallel. This means that our program must keep track of the relationship between the elements of the two arrays but that isn't too difficult since the subscripts match up.
Suppose we want to store more than one mark for each of our students. We don't want to declare any more one-dimensional arrays because it will make our program very time-consuming to write when we want to process this information. Instead, we declare an array with two dimensions to store the values.
This would give us something like this,
Element | Exam Mark 0 | Exam Mark 1 | Exam Mark 2 | Exam Mark 3 | Exam Mark 4 |
0 | 37 | 51 | 65 | 69 | 56 |
1 | 52 | 39 | 40 | 41 | 57 |
2 | 41 | 33 | 32 | 75 | 77 |
3 | 74 | 43 | 45 | 50 | 73 |
4 | 61 | 76 | 35 | 57 | 41 |
5 | 87 | 74 | 47 | 65 | 53 |
6 | 53 | 57 | 36 | 33 | 55 |
7 | 29 | 68 | 79 | 61 | 64 |
We can declare, initialise and iterate through the two-dimensional array as follows,
int[,] examMarks = { { 37, 51, 65, 69, 56 }, { 52, 39, 40, 41, 57 }, { 41, 33, 32, 75, 77 }, { 74, 43, 45,
50, 73 }, { 61, 76, 35, 57, 41 }, { 87, 74, 47, 65, 53 }, { 53, 57, 36, 33, 55 }, { 29, 68, 79, 61, 64 } };
for (int i = 0; i < examMarks.GetLength(0); i++)
{
Console.Write("Marks for student {0}: ", i);
for (int j = 0; j < examMarks.GetLength(1); j++)
{
Console.Write("{0} ",examMarks[i, j]);
}
Console.WriteLine();
}
Console.ReadLine();
The array declaration is a bit long and breaks over two lines here.