Creating and Accessing Arrays:
A variable (or simple variable) is a name to which Visual Basic can assign a single value. An array
variable is a collection of simple variables of the same type to which Visual Basic can efficiently
assign
a list of values.
Consider the following situation: Suppose that you want to evaluate the exam grades for 30
students.
Not only do you want to compute the average score, but you also want to display the names of the
students whose scores are above average. You might place the 30 pairs of student names and scores
in a
text file and run the program outlined:
Private Sub btnDisplay_Click(...) Handles [Link]
Dim student1 As String, score1 As Double
Dim student2 As String, score2 As Double
Dim student3 As String, score3 As Double
Dim student30 As String, score30 As Double
'Analyze exam grades
Dim sr As [Link] = [Link]("[Link]")
student1 = [Link]
score1 = CDbl([Link])
student2 = [Link]
score2 = CDbl([Link])
student30 = [Link]
score30 = CDbl([Link])
[Link]()
'Compute the average grade
.
'Display names of above average students
End Sub
This program is going to be uncomfortably long. What's most frustrating is that the 30 Dim
statements
and 30 pairs of statements reading from the file are very similar and look as if they should be
condensed
into a short loop. A shorthand notation for the many related variables would be welcome. It would
be
nice if we could just write
For i As Integer = 1 To 30
studenti = [Link]
scorei = CDbl([Link])
Next
Of course, this will not work. Visual Basic will treat studenti and scorei as two variables and keep
reassigning new values to them. At the end of the loop, they will have the values of the thirtieth
student.
Declaring an Array Variable
Visual Basic provides a data structure called an array that lets us do what we tried to accomplish in
the
loop. The variable names, similar to those in the preceding program, will be
student(0), student(1), student(2), student(3), ..., student(29)
and
score(0), score(1), score(2), score(3), ..., score(29)
We refer to these collections of variables as the array variables student() and score(). The numbers
inside the parentheses of the individual variables are called subscripts, and each individual variable is
called a subscripted variable or element . For instance, student(3) is the fourth subscripted variable
of the
array student(), and score(20) is the 21st subscripted variable of the array score(). The elements of
an
array are assigned successive memory locations. Figure 7.1 shows the memory locations for the
array
score()
Array variables have the same kinds of names as simple variables. If arrayName is the name of an
array
variable and n is an Integer literal, variable, or expression, then the declaration statement
Dim arrayName(n) As varType
reserves space in memory to hold the values of the subscripted variables arrayName(0),
arrayName(1),
arrayName(2), ..., arrayName(n). The value of n is called the upper bound of the array. The number
of
elements in the array,n+1, is called the size of the array. The subscripted variables will all have the
same
data type; namely, the type specified by varType. For instance, they could be all String variables or
all
Integer variables. In particular, the statements
Dim score(29) As Double
Dim score(29) As Double
declare the arrays needed for the preceding program.
Values can be assigned to individual subscripted variables with assignment statements and displayed
in
text boxes and list boxes just as values of ordinary variables. The default initial value of each
subscripted variable is the same as with an ordinary variable; that is, the keyword Nothing for String
types and 0 for numeric types. The statement
Dim score(29) As Double
For i As Integer = 0 To 2
[Link](score(i))
Next
then produce the following output in the list box:
87
92
As with an ordinary variable, an array declared in the Declarations section of the Code
window is classlevel. That is, it will be visible to all procedures in the form, and any value assigned to
it in a procedure
will persist when the procedure terminates. Array variables declared inside a procedure are
local to that
procedure and cease to exist when the procedure is exited.
Example 1.
The Load Event Procedure
In Example 1, the array teamName was assigned values within the btnWhoWon_Click event
procedure.
Every time the button is clicked, the values are reassigned to the array. This manner of assigning
values
to an array can be very inefficient, especially in programs with large arrays where the task of the
program (in Example 1, looking up a fact) may be repeated numerous times for different user input.
When, as in Example 1, the data to be placed in an array are known at the time the program begins
to
run, a more efficient location for the statements that fill the array is in the form's Load event
procedure.
The Load event occurs automatically when the form is loaded into memory, before it becomes
visible on
the screen. The header and End Sub statements for the Load event procedure are placed in the Code
window when you double-click on the form. A typical header looks like
Private Sub frmName_Load(...) Handles [Link]
The keyword MyBase is similar to the Me keyword and refers to the form being loaded. Example 2
uses
the frmBowl_Load procedure to improve on Example 1.
The following improvement on Example 1 makes teamName () a class-level array and
assigns values to the elements of the array in the frmBowl_Load procedure:
Dim teamName(3) AsString
Private Sub btnWhoWon_Click(...) Handles [Link]
Dim n As Integer
n = CInt([Link])
[Link] = teamName(n - 1)
End Sub
Private Sub frmBowl_Load(...) [Link]
'Place Super Bowl Winners into the array
teamName(0) = "Packers"
teamName(1) = "Packers"
teamName(2) = "Jets"
teamName(3) = "Chiefs"
End Sub
Like ordinary variables, array variables can be declared and assigned initial values at the same time.
statement of the form
Dim arrayName() As varType = {value0, value1, value2, ..., valueN}
declares an array having upper bound N and assigns value0 to arrayName(0), value1 to
arrayName(1),
value2 to arrayName(2), ..., and valueN to arrayName(N). For instance, in Example 4, the Dim
statement and frmBowl_Load event procedure can be replaced by the single line
Dim teamName() As String = {"Packers", "Packers", "Jets", "Chiefs"}
The GetUpperBound Method
The value of [Link](0) is the upper bound of the array. For instance, in Example
1,
the value of [Link](0) is 3.
ReDim Statement
After an array has been declared, its size (but not its type) can be changed with a statement of the
form
ReDim arrayName(m)
where arrayName is the name of the already declared array and m is an Integer literal, variable, or
expression. Note: Since the type cannot be changed, there is no need for an "As dataType" clause at
the
end of the ReDim statement.
Visual Basic allows you to declare an array without specifying an upper bound with a statement of
the formThe ReDim statement has one shortcoming: It causes the array to lose its current contents.
That is, it
resets all String values to Nothing and resets all numeric values to 0. This situation can be remedied
by
following ReDim with the word Preserve. The general form of a ReDim Preserve statement is
ReDim Preserve arrayName(m)
Of course, if you make an array smaller than it was, data in the eliminated elements will be lost.
Example 3.
The following program reads the names of the winners of Super Bowl games from a file and
places them into an array. The user can type a team's name into a text box and then display
the numbers of the Super Bowl games won by that team. The user has the option of adding
winners of subsequent games to the array of winners. The program uses the text file
[Link] whose lines contain the names of the winners in order. That is, the first
four lines of the file contain the names Packers, Packers, Jets, and Chiefs.
Dim teamName() AsString
Dim upperBound As Integer
Private Sub frmBowl_Load(...) [Link]
Dim sr As [Link] = [Link]("[Link]")
Dim name As String, numLines As Integer
'Count number of lines in the file and assign it minus one to upperBound
numLines = 0
Do While ([Link] <> -1)
name = [Link]
numLines += 1
Loop
upperBound = numLines -1
[Link]()
'Specify the title bar of the form
[Link] = "First " & upperBound + 1 & " Super Bowls"
'Specify the caption of the Next Winner button
[Link] = "Add Winner of Game " & upperBound + 2
'Specify the size of the array and fill it with the entries of the file
ReDim teamName(upperBound)
sr = [Link]("[Link]")
For i As Integer = 0 To upperBound
teamName(i) = [Link]
Next
[Link]()
End SubPrivate Sub btnDisplay_Click(...) Handles [Link]
'Display the numbers of the games won by the team in the text box
[Link]()
For i As Integer = 0 To upperBound
If teamName(i) = [Link] Then
[Link](i + 1)
End If
Next
End Sub
Private Sub btnNextWinner_Click(...) Handles [Link]
'Add winner of next Super Bowl to the array
Dim prompt As String
upperBound += 1
'Add one more element to the array
ReDim Preserve teamName(upperBound)
'Request the name of the next winner
prompt = "Enter winner of game #" & upperBound + 1
teamName(upperBound) = InputBox(prompt, , "")
'Update the title bar of the form and the caption of the button
'Note: "Me" refers to the form.
[Link] = "First " & upperBound + 1 & " Super Bowls"
[Link] = "Add Winner of Game " & upperBound + 2
End Sub
[Run, type "49ers" into the text box, and press the Display button. Then, feel free to add
subsequent winners. Your additions will be taken into account when you next press the
Display button.]
1. Write code to declare an array with upper bound 10 and place the names of the five
programming Languages into the first five elements. Use one or two lines of code.
2. In Example 3, rewrite the btnDisplay_Click event procedure so that only the first Super
Bowl won by the requested team is displayed. The loop should terminate when the team
is found.
3. When should arrays be used to hold data?
1. What is the size of an array whose upper bound is 100?
2. What is the upper bound of an array whose size is 100?
3. Private Sub btnDisplay_Click(...) Handles [Link]
Dim num As Integer = 2
Dim spoon(num) As String
spoon(0) = "soup"
spoon(1) = "dessert"
spoon(2) = "coffee"
[Link] = "Have a "& spoon(num - 1) & " spoon."
End Sub
4. Private Sub btnDisplay_Click(...) Handles [Link]
Dim a(20) As Integer
a(5) = 1
a(10) = 2
a(15) = 7
[Link](a(5) + a(10))
[Link](a(5 + 10))
[Link](a(20))
End Sub
5. Dim sq(5) As Integer
Private Sub btnDisplay_Click(...) Handles [Link]
Dim t As Integer
For i As Integer = 0 To 5
sq(i) = i * i
Next
[Link](sq(3))
t=3
[Link](sq(5 - t))
End Sub
[Link] fh(3) As String
Private Sub btnDisplay_Click(...) Handles [Link]
Dim n As Integer
Dim sr As [Link] = [Link]("[Link]")
For i As Integer = 0 To 3
fh(i) = [Link]
Next
[Link]()
[Link](fh([Link](0)))
n=1
[Link](fh(2 * n))
End Sub(Assume that the four lines of the file [Link] contain the following entries:
Miller, Layden, Crowley, Stuhldreher.)
[Link] s(3) As Integer
Private Sub btnDisplay_Click(...) Handles [Link]
Dim t As Integer
Dim sr As [Link] = [Link]("[Link]")
t=0
For k As Integer = 0 To 3
s(k) = CInt([Link])
t += s(k)
Next
[Link] = CStr(t)
[Link]()
End Sub
(Assume that the four lines of the file [Link] contain the following entries: 3, 5, 2,
1.)
[Link] a(3), b(3) As Integer
Dim c(3) As Double
Private Sub btnDisplay_Click(...) Handles [Link]
Dim sr As [Link] = [Link]("[Link]")
For i As Integer = 0 To 3
a(i) = CInt([Link])
b(i) = CInt([Link])
Next
[Link]()
For i As Integer = 0 To [Link](0)
c(i) = a(i) * b(i)
[Link](c(i))
Next
End Sub
(Assume that the eight lines of the file [Link] contain the following entries: 2, 5, 3,
4, 1, 3, 7, 2.)
9. Private Sub btnDisplay_Click(...) Handles [Link]
'Compare the values of two chess pieces
Dim chess() As string = {"king", "queen", ""}
chess(2) = "rook"
ReDim Preserve chess(6)
chess(3) = "bishop"
[Link] = "A "& chess(2) & " is worth more than a "_
& chess(3)
End Sub
[Link] grade(1) As Double
Private Sub btnDisplay_Click(...) Handles [Link]
Dim average As Double
ReDim grade(3)
grade(2) = 70
grade(3) = 80
average = (grade(0) + grade(1) + grade(2) + grade(3)) / 4
[Link] = "Your average is "& average
End Sub
Private Sub frmGrades_Load(...) Handles [Link]
grade(0) = 89
grade(1) = 91
End Sub
11. Dim score() As Double = {71, 68, 69}
Private Sub btnDisplay_Click(...) Handles [Link]
'Find the sum of four scores
Dim total As Double
ReDim Preserve score(3)
score(3) = 72
total = score(0) + score(1) + score(2) + score(3)
[Link] = "Your total is "& total & "."
End Sub
12. Dim band() As String = {"soloist", "duet", "trio", "quartet"}
Private Sub btnDisplay_Click(...) Handles [Link]
Dim num As Integer
ReDim Preserve band(9)
band(4) = "quintet"
band(5) = "sitet"
band(6) = InputBox("What do you call a group of 7 musicians?")
num = CInt(InputBox("How many musicians are in your group?"))
[Link] = "You have a "& band(num - 1) & "."
End Sub
13. Dim companies(100) As String
Private Sub frmFirms_Load(...) Handles [Link]
Dim recCount Integer
Dim sr As [Link] = [Link]("[Link]")
recCount = CInt([Link])
ReDim companies(recCount - 1) As String
For i As Integer = 0 To recCount - 1
companies(i) = [Link]
Next
[Link]()
End Sub
14. Dim p(100) As Double
Private Sub btnDisplay_Click(...) Handles [Link]
For i As Integer = 0 To 200
p(i) = i / 2
Next
End Sub
15. Dim a(10) As Integer
Private Sub btnDisplay_Click(...) Handles [Link]
Dim sr As [Link] = [Link]("[Link]")
For i As Integer = 0 To 8
a(i) = CInt([Link])
Next
[Link]()
For k As Integer = 0 To 8
a(k) = a(5 - k)
Next
End Sub
(Assume that the nine lines of the file [Link] contain the following entries: 1, 2, 3,
4, 5, 6, 7, 8, 9.)