Visual C# Guide
Two-Dimensional Arrays

One-Dimensional Arrays In Parallel

The examples on the previous page all refer to arrays with a single dimension. Consider the following representation of a one-dimensonal array,

ElementStudent
0Pinky
1Perky
2Bob
3Agnes
4Bill
5McJack
6Jimbob
7Gladys

Imagine that we want to store several pieces of information about each of the students, say an exam mark. We can start by declaring another one-dimensional array of integers and store each mark in the correct place so that,

ElementExam Mark
037
152
241
374
461
587
653
729

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.

Two-Dimensional Arrays

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,

ElementExam Mark 0Exam Mark 1Exam Mark 2Exam Mark 3Exam Mark 4
03751656956
15239404157
24133327577
37443455073
46176355741
58774476553
65357363355
72968796164

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.

Having A Go

  1. Copy the declaration of the exam marks array. Create an array of student names to match up with this data. Calculate the total and mean average for each student.