After going through a grilling session on variables and constants, let us
focus our attention on larger data types. In case we just want to define a
variable to store one value, then we can do with single variables discussed
earlier. But on numerous occasions, you will feel the need for a data type that
can store multiple values of the same type. For example 100 students of a class,
11 players of a cricket team, etc. Here arrays come into picture.
Arrays
Variables are useful for storing small pieces of information, but not good
for large amounts of very similar information. For example, to hold the salaries
of two hundred employees would require 200 different variable names. A much more
efficient way is to use a data structure called an array.
An array is similar to a row of pigeon-holes. The whole array has one name,
and each pigeon-hole has an address. For the above salaries problem we
need an array which has 200 elements (pigeon-holes). To do this we use
the Dim command that we used to create new variables. However, a size
is also allocated.
Dim array_name (size) [As Type]
Example: Dim students(99) As
Long
The above example creates an array with 100 elements. The size is set to 199
because by default VB starts numbering from 0 (Just like C).
If we know that 'Fred' is student number 24 and has scored of 25 marks, then we can enter this amount into the array using:
marks(23) =25
Conversely, if we want to know how much student no 89 has scored, then we can use:
score.Caption =marks(88)
Dynamic Arrays
There may be times when writing an application, however, when a program needs
to change the size of the array. To do this a 'dynamic' array can be used.
First the array must be declared in the same way but without a number of
elements specified:
Dimbooks() As String
To change the size of this array use the 'ReDim' command and a
specific number of elements:
ReDimbooks(99)
Normally the contents of an array is erased when re-dimensioning, however to
stop this use:
ReDim Preservebooks(99)
Like variables, arrays can also have different scopes:
- Public - available to any form or module contained in the
project.
- Module - available to any procedure on the form on which it
is placed.
- Procedure - available only within the procedure in which it
is declared.
In the next article, we shall study about statements in Visual Basic.
The copyright of the article
Arrays in VB in
Learning Visual Basic is owned by Swapna Kamat. Permission to republish
Arrays in VB in print or online must be granted by the author in writing.