Introduction to Arrays

by Michael Anderson

Summary of Sections 7.1 & 7.2

7.1: Motivation for Arrays;
Declaring arrrays: Dim var(0 to 30) As varType
Redim var(0 to n) As varType
Dim var() As varType

7.2: Using Arrays: Searching, passing, LBound(), UBound()

 

Motivation for Arrays

Arrays are used quite commonly when reading data from a file. They avoid typing (nearly) identical statements over and over again, and provides the flexibility to handle variable numbers of items.

Arrays are used in many other situations, for example:

keeping track of the names of months (accounting programs)

whenever data needs to be sorted

when performing statistical analysis of numerical data

What other examples can you imagine?

Declaring Arrays

Arrays are most commonly declared with a statement like:

Dim FirstNames( 1 To 25 ) As String

which creates an array of 25 strings for storing people's first name.

This is one example of a situation where numeric values can not readily be substituted for a variable.

The subscript range for an array can be any range of values, as long as the lower bound (LBound) is less than the upper bound (UBound).

In C-language, the lower array bound always starts at zero (0).

In VB, if you can abbreviate the above statement to:
Dim FirstNames( 25 )
when the lower bound is assumed to be zero (0).

Trap! Watch for off-by-one errors when determining the size of an array. Use UBound–LBound + 1 to get the correct size.

Redimensioning Arrays

Under some circumstances, it is necessary to redimension an array. This can only be done inside procedures, and not for form-level (ie. global) arrays. The advantage of redimensioning is that you can use variables or expressions to set the size of the array. eg.

ReDim FirstNames( 1 to maxNames ) As String

In some circumstances, you know in advance that you will need to redimension a form-level array. In this case, declare the array in the General Section as:
Dim FirstNames() As String
Such an array must be ReDim'ed before its first use!

Searching Arrays

"For" and "while" loops are commonly used for reading input values for an array, and then searching through the array to find matching value(s).

The simple framework for such a procedure is:

Let target = txtTarget.text
Let i = 1
Do While ( i < arrayLimit )
   If ( array(i) = target ) Then
   picBox.print "The matching value is "; i
End If
Loop

Passing Arrays

Arrays can be passed into a function just like any other variable. Inside the function they are declared without any dimensions; eg.

Private Sub DemoProc( arrayVar() As String )

In order to know exactly what index values are possible, you can use the two operators "LBound" and "UBound". eg.

For i = LBound(arrayVar) To UBound(arrayVar) step 1

. . .

Next i

This avoids the nuisance of having to manually pass in the lower and upper limit values.