Arrays in VB


© Swapna Kamat
Articles in this Topic    Discussions in this Topic

Arrays in VB

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:

  1. Public - available to any form or module contained in the project.
  2. Module - available to any procedure on the form on which it is placed.
  3. Procedure - available only within the procedure in which it is declared.

In the next article, we shall study about statements in Visual Basic.

Go To Page: 1


Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo