Overview of Arrays

Arrays:

 

Justification:

Example:
  • A program is required to store and print 1000 pieces of related data, such as pressure readings from some manufacturing process. 
  • If individually named variables are used for each data item, then the program must have 1000 unique variable names and 1000 separate print statements to print those individual data items.
  • A one-dimensional array is a structured data type that is provided to help programmers code operations such as this with ease.

 

=========================================================

Declaration:
        Dim array_name (upper_bound) As component_type      

Example:
        Dim grade (35) As Integer

=========================================================

Component_type indicates what can be stored in each element of the array.

The upper_bound is the highest valid index.

The array has upper_bound + 1 elements, because the lower_bound defaults to 0.

Individual numeric array elements are initialized to zero by default.

When specifying the upper_bound, using a constant  like SIZE instead of a number makes it easier to change the array size: only one program line needs to be changed to change the array size, loop limits, etc.

Attempting to access an index that is smaller than the lower bound or larger than the upper bound is a run-time error.

 

 

=========================================================

To access a particular element in an array use the following syntax:
        Array_name(constant or variable) 

Example:
        Print (Grade(ctr)) 

=========================================================

Example:
        Dim grade (35) As Integer

 

 

 

 


                                          

 

                                             

 

                                             

 

 

 

 

=========================================================

Processing arrays


To process an array element by element, you can use a For loop.

 

For ctr = 0 to 35

     Print Grade(ctr) & Space$(2);

Next ctr

 

Or

 

For ctr = LBound(Grade)  to UBound(Grade)

     Print Grade(ctr) & Space$(2);

Next ctr

 

Function LBound returns the lowest-numbered index value.

 

Function UBound returns the highest_numbered index value.

 

=========================================================

Accessing array elements

 

To access an element of an array, use the array name and an index.

 

The index can be a variable, constant, or expression of type Long , and indicates the location of the element that will be referenced.

 

 

A For loop can be used to process all elements of an array.  If an application requires either processing all elements in the array or stopping if a certain condition is detected, one of the forms of While loops must be used.

 

The following example checks all students in a class to determine whether everyone is passing.  If a failing student is detected, processing can be terminated because it has been determined that everyone is not passing.  Therefore a While loop is used.

 

All_Passing = True

Ctr = 0

While (Ctr <= 35) And All_Passing

    If (Grade(Ctr) < 70) Then

           All_Passing = False

    Else

            Ctr = Ctr + 1

    EndIf

Wend

 

=========================================================

Example:

 

Dim studentGrade (9) As String

 

Sample contents after some processing:

 

studentGrade

 

"F"

"B"

"C"

"A"

"F"

"C"

"A"

"A"

"C"

"B"

 

studentGrade(4) = "F"

Assigns "F" to the fifth cell in the array studentGrade.

 

 

ID = 6

studentGrade(ID) = "A"

Assigns "A" to the seventh cell in the array studentGrade.

 

For ID = 0 to 9

      Print studentGrade(ID);

Next ID

The loop prints all the values in studentGrade:  FBCAFCAACB

 

For ID = 0 to 9

      Print "Student " & ID+1 & "Grade " & studentGrade(ID)

Next ID

The loop prints all the values in studentGrade in a more readable form.  ID is used as the index, but also serves as the student's identification number.

Student 1  Grade F

Student 2  Grade B

  :

  :

Student 10 Grade B

 

=========================================================

Option Base

 

=========================================================

Declaring Arrays with the To Keyword

 

Arrays can be declared by using the To keyword within the subscript syntax.

For example, if you want to create an array of five Integer variables in which the first element has index 1 and the last element has index 5, you could use

Dim fiveArray(1 To 5) as Integer

For example, if you want to create an array of Integer variables to track the number of students scheduled to graduate during the first six years after the year 2000, you could use

 Dim arrayY2K(2000 To 2005) as Integer

=========================================================

Determining array size

 

The number of elements in an array can be determined using the following formula:

 

      UBound (array) - LBound (array) + 1

 

=========================================================

Bounds checking in arrays

 

If an attempt is made to access an element outside of the array bounds, it is a run-time error. i.e., Visual Basic performs bounds checking on array subscripts.

 

For example, given the declaration Dim grade (35) As Integer, an attempt to access grade(ctr) when ctr has a value of 36 would be a run-time error.

=========================================================

Examples using arrays

 

The program below uses a For to print the contents of the ten-element Integer array n.

 

==============

 

The next program initializes the elements of the ten-element Integer array s to 2, 4, 6, ...,20, and prints the array element contents in a tabular format.

 

==============

 

The following program uses arrays to summarize the results of data collected in a survey.  The problem statement stipulates

 

Forty students were asked to rate the quality of the food in the student cafeteria on a scale of 1 to 10 (10 meaning excellent). Place the 40 responses in an integer array and summarize the results of the poll.

 

Random numbers

  • The VB function Rnd returns a Single random number in the range 
    0
    <  Rnd <1.

  • This program requires numbers in the range of 1-10, and the statement Int(Rnd( ) * 10) produces numbers in the range 0 to 9, with the number 10 acting as the scaling factor.  By adding 1 to the result with the statement 
    1 + Int(Rnd( ) * 10),
    the result is shifted to produce numbers in the range of 1 to 10.

  • In order to insure that Rnd generates random numbers, the Randomize statement can be used to seed the Rnd function to produce a different sequence of random numbers each time Randomize is used.  The seed its the initial number that the random number generator uses to produce a series of random numbers.

 

 

Procedure cmdPrint_Click calculates and prints the frequency of each response.

The first For loop takes each response from mResponses and increments one of the ten frequency counters--frequency(1) to frequency(10).

The statement frequency(mResponses(x)) = frequency(mResponses(x)) + 1 increments the appropriate frequency counter depending on the value of mResponses(x).  

Regardless of the number of responses in the survey, only a ten-element array is required to summarize the results, because there are only 10 possible responses.

 

=========================================================

Arrays in procedures

 

=========================================================

 

Passing Arrays to Procedures 

entire arrays:
To pass an array argument to a procedure, specify the name of the array followed by a pair of empty parentheses.

For example, if array hourlyTemperatures is declared as 

            Dim hour1yTemperatures(24) As Integer 

the call 

Call ModifyArray(hourlyTemperatures( )) 

passes array hourlyTemperatures to procedure ModifyArray.

array elements:
To pass an element of an array to a procedure, use the array element as an argument in the call. 

For example, the call 

Call PassOneElement(hourlyTemperatures(5))

would pass the array element corresponding to index 5 to PassOneElement.

=========================================================

 

Receiving Arrays in Procedures 

entire arrays:
For a procedure to receive an array through a call, the parameter list must specify that an array will be received.

For example, the procedure header for ModifyArray might be written as

 

   Private Sub ModifyArray(a( ) As Integer)

indicating that ModifyArray expects to receive an Integer array in parameter a.

The size of the array is not specified between the array parentheses.

array elements:
For a procedure to receive an array element from a call, the procedure declares a variable of the type passed.

For example, the procedure header for PassOneElement might be written as

 

Private Sub PassOneElement(k as Integer)

Variable k refers to hourlyTemperatures (5).

 =========================================================

Examples of arrays as parameters

The program below demonstrates passing an array and passing array elements to a procedure.

Line 16's procedure call, 

Call ModifyArray(mArray( ))

passes mArray by-reference to ModifyArray, where mArray's elements are then multiplied by 2.

The call, 

Call ModifyE1ement (mArray(x))

passes each individual array element one at a time to ModifyElement by-reference where each element is multiplied by 5 and the result is stored in the element itself.