Often we may want to store and manipulate a large set of numbers (for example the marks for a number of students in an exam). It is clearly not convenient to give a new variable name to each student's mark, so arrays are introduced for this purpose. An array is just like a vector; i.e. it has many components. Below is an example of a program which uses arrays.
Dim Marks(100) As Double Dim I, N As Long ' First the Marks are read in from a file Open "Exam.dat" For Input As #2 N = 0 While Not EOF(2) N = N + 1 Input #2, Marks(N) Wend ' Then the sum of the Marks is calculated and the average found Sum = 0 For I = 1 To N Sum = Sum + Marks(I) Next I Print "The average mark is ", Sum / N
The very first instruction Dim Marks(100) As Double tells the
computer to set aside memory for an array called Marks which
will have (a maximum of) 100 real-valued elements. Then the marks are
read from the file Exam.dat. (See for an
explanation of reading in data from a file using the While Not
EOF statement.) The next step in the code is to calculate the sum of
all the N students marks using a For/Next loop. (See
for an explanation of using the For/Next loop to
sum up some numbers). Finally the average mark Sum / N is
outputted to the screen.
CHECKPOINT: Using the above examples, write a program which finds the largest mark from data in the file Exam.dat.
Note that it is possible to have more than one dimension in the array. Consider the following:
Dim A(20,100,5) As Long For I = 1 To 10 For J = 1 To 100 For K = 1 To 5 A(I,J,K) = ... Next K Next J Next I
In this case, the array A is a 3-dimensional array, and the elements of A are accessed within the three nested For/Next loops. Note that the I loop only goes up to 10, whereas the corresponding dimension of A (i.e. the first dimension) has a maximum value of 20, i.e. you don't have to access all the elements of the array.
You can pass arrays to subroutines using the following. (Note, for
information on subroutines, see sec..)
. . . call add( x(), n, total ) . . . sub add( x(), n, sum ) Dim i as Long sum = 0. For i = 1 To n sum = sum + x(i) Next i end sub
Note that in the above example that
I've included a small programme which uses a subroutine call with an array as an argument to find the minimum of that array. Click here to download it.
Arrays can be used as a convenient way of storing more than
one piece of data within a single variable name. They are the
computing equivalent of vectors or matrices. You can have arrays of
any data type: e.g. Double, Long, String see .