Visual Basic 2010 (Console) 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,
Element | Student |
0 | Pinky |
1 | Perky |
2 | Bob |
3 | Agnes |
4 | Bill |
5 | McJack |
6 | Jimbob |
7 | Gladys |
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,
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.
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,
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,
Dim examMarks(,) As Integer = {{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 student = 0 To examMarks.GetLength(0) - 1
Console.Write("Marks for student {0}: ", student)
For mark = 0 To examMarks.GetLength(1) - 1
Console.Write("{0} ", examMarks(student, mark))
Next
Console.WriteLine()
Next
Console.ReadLine()
Having A Go
- 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.