1
8
Arrays
2009 Pearson Education, Inc. All rights reserved.
2
Now go, write it before them in a table,
and note it in a book.
– Isaiah 30:8
With sobs and tears he sorted out
Those of the largest size …
– Lewis Carroll
Attempt the end, and never stand to doubt;
Nothing’s so hard, but search will find it out.
– Robert Herrick
2009 Pearson Education, Inc. All rights reserved.
3
Begin at the beginning, ... and go on
till you come to the end: then stop.
– Lewis Carroll
To go beyond is as wrong as to fall short
– Confucius
2009 Pearson Education, Inc. All rights reserved.
4
OBJECTIVES
In this chapter you will learn:
To use the array data structure; arrays are
objects.
How arrays are used to store, sort and search
lists and tables of values.
To declare, initialize and refer to individual
elements of arrays.
To pass arrays to methods using ByVal and
ByRef.
2009 Pearson Education, Inc. All rights reserved.
5
OBJECTIVES
To declare and manipulate multidimensional
arrays, especially rectangular arrays and
jagged arrays.
To create variable-length parameter lists.
To use the For Each…Next statement to
iterate through the elements of arrays without
using a loop counter.
2009 Pearson Education, Inc. All rights reserved.
6
8.1
Introduction
8.2
Arrays
8.3
Declaring and Allocating Arrays
8.4
Examples Using Arrays
8.5
Case Study: Card Shuffling and Dealing Simulation
8.6
Passing an Array to a Method
8.7
For Each…Next
8.8
GradeBook
Repetition Statement
Case Study: Using an Array to Store
Grades
8.9
Sorting an Array with Method Sort of Class Array
2009 Pearson Education, Inc. All rights reserved.
7
8.10 Searching Arrays
8.11 Rectangular Arrays
8.12 GradeBook Case Study: Using a Rectangular Array
8.13 Variable-Length Parameter Lists
8.14 Jagged Arrays
8.15 Changing the Size of an Array at Execution Time:
Using the ReDim Statement
8.16 Passing Arrays: ByVal vs. ByRef
8.17 (Optional) Software Engineering Case Study:
Collaboration Among Objects in the ATM System
2009 Pearson Education, Inc. All rights reserved.
8
8.2 Arrays
• An array is a group of variables (elements) containing
values of the same type.
• The first element is the zeroth element. The elements
of array c are c(0), c(1), c(2) and so on.
• The position number in parentheses is more formally
called an index (or a subscript).
2009 Pearson Education, Inc. All rights reserved.
9
8.2 Arrays (Cont.)
• Figure 8.1 shows a representation of an integer array called c.
Fig. 8.1 | Array consisting of 12 elements.
2009 Pearson Education, Inc. All rights reserved.
10
8.2 Arrays (Cont.)
Common Programming Error 8.1
Array indices begin at 0, which means that the “seventh
element of the array” has the index 6, whereas “array
element seven” has the index 7 and is actually the eighth
element of the array.
We refer to all array elements simply by their indexed
names—such as c(0) rather than “the first element of c.”
2009 Pearson Education, Inc. All rights reserved.
11
8.2 Arrays (Cont.)
• The length of array c is determined by the
following expression:
c.Length
• Method GetUpperBound returns the index of the
last element in the array (one less than the length):
c.GetUpperBound(0)
2009 Pearson Education, Inc. All rights reserved.
12
8.3 Declaring and Allocating Arrays
• To declare an array, provide the name and type:
Dim c As Integer()
Dim c() As Integer
• The parentheses indicate that c is an array.
• Arrays are objects, so they must be allocated using keyword
New:
c = New Integer(11) {}
c = New Integer(0 To 11) {}
• Array bounds determine what indices can be used. In both
examples the array bounds are 0 and 11.
Common Programming Error 8.2
Explicitly setting the lower bound of an array to a value other
than 0 is a compilation error.
2009 Pearson Education, Inc. All rights reserved.
13
8.3 Declaring and Allocating Arrays
(cont.)
• The braces ({ and }) specify the initial values of the
elements in the array.
Dim numbers As Integer()
numbers = New Integer() {1, 2, 3, 6}
• The two preceding statements can be combined into a
single statement:
Dim numbers As Integer() = New Integer() {1, 2, 3, 6}
• This can be shortened further:
Dim numbers As Integer() = {1, 2, 3, 6}
Dim numbers(5) As Integer
2009 Pearson Education, Inc. All rights reserved.
14
Outline
• The program in Fig. 8.2 uses the New operator to allocate
an array of 10 Integer elements.
CreateArray.vb
1
' Fig. 8.2: CreateArray.vb
2
3
4
' Declaring and allocating an array.
Module CreateArray
Sub Main()
5
6
7
8
Dim array As Integer() ' declare array variable
' allocate memory for 10-element array using explicit array bounds
array = New Integer(0 To 9) {}
9
10
Console.WriteLine("Index " & vbTab & "Value")
11
12
13
' display values in array
For i = 0 To array.GetUpperBound(0)
14
15
16
17
Console.WriteLine(i & vbTab & array(i))
Next
Console.WriteLine(vbNewLine & "The array contains " & _
18
array.Length & " elements.")
19
End Sub ' Main
20 End Module ' CreateArray
( 1 of 2 )
array can reference an array
of Integers.
Initializing array to an array
of Integers.
The For statement displays
the index and value of each
element.
Length returns the number
of elements in the array.
Fig. 8.2 | Creating an array. (Part 1 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
15
Outline
CreateArray.vb
Index
0
1
2
3
4
5
6
7
8
9
Value
0
0
0
0
0
0
0
0
0
0
( 2 of 2 )
The array contains 10 elements.
Fig. 8.2 | Creating an array. (Part 2 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
16
Outline
• Figure 8.3 creates two 10-element integer arrays and sets their
element values.
InitArray.vb
1
2
3
4
5
6
' Fig. 8.3: InitArray.vb
' Initializing arrays.
Module InitArray
( 1 of 2 )
Sub Main()
' initializer list specifies the number of elements
' and the value of each element
7
8
9
10
Dim array1 As Integer() = _
{32, 27, 64, 18, 95, 14, 90, 70, 60, 37}
11
Dim array2 As Integer() = New Integer(array1.GetUpperBound(0)) {}
12
13
14
' set values in array2 by a calculation
For i = 0 To array2.GetUpperBound(0)
15
16
17
18
array1 is initialized to a
new array.
' allocate array2 based on length of array1
array2(i) = 2 + 2 * i ' generate 2, 4, 6, ..., 20
Next
array2 is initialized to be
the same length as array1.
Initializing the elements in
array2 to even integers 2-20.
Console.WriteLine("Index " & vbTab & "Array1" & vbTab & "Array2")
19
Fig. 8.3 | Initializing array elements with an array initializer
and a For statement. (Part 1 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
17
Outline
20
21
' display values for both arrays side by side
For i = 0 To array1.GetUpperBound(0)
22
Console.WriteLine(i & vbTab & array1(i) & vbTab & array2(i))
23
Next
24
End Sub ' Main
25 End Module ' InitArray
Index
0
1
2
3
4
5
6
7
8
9
Array1
32
27
64
18
95
14
90
70
60
37
InitArray.vb
( 2 of 2 )
Array2
2
4
6
8
10
12
14
16
18
20
Fig. 8.3 | Initializing array elements with an array initializer
and a For statement. (Part 2 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
18
Outline
SumArray.vb
1
2
3
4
5
' Fig. 8.4: SumArray.vb
' Computing the sum of the elements in an array.
Module SumArray
Sub Main()
Dim array As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
6
7
8
9
Dim total As Integer = 0
10
total += array(i)
11
12
13
' sum the array element values
For i = 0 To array.GetUpperBound(0)
array is initialized to an
array of Integers.
The For... statement sums the
elements of array.
Next
Console.WriteLine("Total of array elements: {0}", total)
14
End Sub ' Main
15 End Module ' SumArray
Total of array elements: 55
Fig. 8.4 | Computing the sum of the elements in an array.
2009 Pearson Education,
Inc. All rights reserved.
19
8.4 Examples Using Arrays (Cont.)
8.4.4 Using Arrays to Analyze Survey Results
• Consider the following problem statement:
Forty students were asked to rate on a scale of 1 to 10 the quality
of the food in the student cafeteria. Place the 40 responses in an
integer array and determine the frequency of each rating.
2009 Pearson Education, Inc. All rights reserved.
20
• This is a typical array-processing application (Fig. 8.5).
1
2
3
4
5
6
7
8
9
10
11
' Fig. 8.5: StudentPoll.vb
' Using arrays to display poll results.
Module StudentPoll
Sub Main()
' student response array (more typically, input at run time)
Dim responses As Integer() = _
{1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, _
7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10}
Outline
StudentPoll.vb
( 1 of 2 )
' response frequency array (indices 0 through 10)
Dim frequency As Integer() = New Integer(10) {}
12
13
14
15
16
17
18
19
20
21
' count frequencies
For answer = 0 To responses.GetUpperBound(0)
frequency(responses(answer)) += 1
Next
The For statement iterates
through responses and
increments frequency.
Console.WriteLine("Rating " & vbTab & "Frequency ")
' display output, ignore element 0 of frequency
For rating = 1 To frequency.GetUpperBound(0)
Console.WriteLine(rating & vbTab & frequency(rating))
22
Next
23
End Sub ' Main
24
25 End Module ' StudentPoll
Fig. 8.5 | Simple student-poll analysis program. (Part 1 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
21
Outline
Rating
1
2
3
4
5
6
7
8
9
10
Frequency
2
2
2
2
5
11
5
7
1
3
StudentPoll.vb
( 2 of 2 )
Fig. 8.5 | Simple student-poll analysis program. (Part 2 of 2.)
Common Programming Error 8.3
When a program is executed, array element indices are checked for
validity. If an attempt is made to use an invalid index to access an
element, Visual Basic generates an IndexOutOfRangeException.
Error-Prevention Tip 8.1
When looping through an array, the array index should remain
between 0 and the upper bound of the array.
2009 Pearson Education,
Inc. All rights reserved.
22
Outline
• Figure 8.6 displays data by creating a bar chart
with asterisks (*).
1 ' Fig. 8.6: BarChart.vb
2 ' Using data to create bar chart.
BarChart.vb
3 Module BarChart
4
Sub Main()
5
' create data array
( 1 of 2 )
6
7
8
9
10
11
12
13
14
15
16
Dim array1 As Integer() = {19, 3, 15, 7, 11, 9, 13, 5, 17, 1}
Console.WriteLIne("Element " & "Value " & vbTab & "Bar Chart")
' display a bar of the bar chart for each element in the array
For i = 0 To array1.GetUpperBound(0)
Console.Write(i & vbTab & array1(i) & vbTab)
For j = 1 To array1(i)
Console.Write("*") ' display one asterisk
Next j
Writing asterisks
representing the value of
each element.
17
18
Console.WriteLine()
19
Next i
20
End Sub ' Main
21 End Module ' BarChart
Fig. 8.6 | Bar chart printing program. (Part 1 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
23
Outline
BarChart.vb
Element
0
1
2
3
4
5
6
7
8
9
Value
19
3
15
7
11
9
13
5
17
1
Bar Chart
*******************
***
***************
*******
***********
*********
*************
*****
*****************
*
( 2 of 2 )
Fig. 8.6 | Bar chart printing program. (Part 2 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
24
Outline
• An array version of the dice roll-counting application
is shown in Fig. 8.7.
1
2
' Fig. 8.7: RollDie.vb
' Rolling 12 dice with frequency chart.
3
Public Class RollDie
4
5
Dim randomNumber As Random = New Random()
Dim frequency As Integer() = New Integer(6) {}
6
7
8
9
10
' event handler for rollButton's Click event
Private Sub rollButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles rollButton.Click
11
12
13
14
15
16
17
' pass PictureBox to a method that assigns a face to each die
DisplayDie(die1PictureBox)
DisplayDie(die2PictureBox)
DisplayDie(die3PictureBox)
DisplayDie(die4PictureBox)
DisplayDie(die5PictureBox)
DisplayDie(die6PictureBox)
18
19
20
DisplayDie(die7PictureBox)
DisplayDie(die8PictureBox)
DisplayDie(die9PictureBox)
RollDie.vb
( 1 of 4 )
Initializing frequency as
an Integer array.
Fig. 8.7 | Using arrays to eliminate a Select Case statement. (Part 1 of 4.)
2009 Pearson Education,
Inc. All rights reserved.
25
Outline
21
22
DisplayDie(die10PictureBox)
DisplayDie(die11PictureBox)
23
DisplayDie(die12PictureBox)
( 2 of 4 )
24
25
Dim total As Double = 0
26
27
28
' total the die faces (used in percentage calculations)
For i = 1 To frequency.GetUpperBound(0)
29
30
31
total += frequency(i)
Next
32
33
34
35
36
37
38
displayTextBox.Text = "Face" & vbTab & "Frequency" & _
vbTab & "Percent" & vbNewLine
39
40
41
RollDie.vb
' output frequency values
For i = 1 To frequency.GetUpperBound(0)
displayTextBox.Text &= i & vbTab & frequency(i) & _
vbTab & vbTab & String.Format("{0:P2}", _
frequency(i) / total) & "%" & vbNewLine
Recording rolls in frequency.
Lines 36–40 replace lines 35–
47 of Fig. 7.17
Next
End Sub ' rollButton_Click
Fig. 8.7 | Using arrays to eliminate a Select Case statement. (Part 2 of 4.)
2009 Pearson Education,
Inc. All rights reserved.
26
Outline
RollDie.vb
42
43
44
45
46
47
48
49
( 3 of 4 )
' simulate roll, display proper image and increment frequency
Sub DisplayDie(ByVal diePictureBox As PictureBox)
Dim face As Integer = 1 + randomNumber.Next(6)
' retrieve specific die image from resources
Dim pictureResource = My.Resources.ResourceManager.GetObject( _
String.Format("die{0}", face))
Producing a random number
from 1 to 6
50
51
52
' convert pictureResource to image type and load into PictureBox
diePictureBox.Image = CType(pictureResource, Image)
53
54
55
frequency(face) += 1 ' increment appropriate frequency counter
End Sub ' DisplayDie
Lines 62–75 of Fig. 7.17 are
replaced by line 54.
56 End Class ' RollDie
Fig. 8.7 | Using arrays to eliminate a Select Case statement. (Part 3 of 4.)
2009 Pearson Education,
Inc. All rights reserved.
27
Outline
RollDie.vb
( 4 of 4 )
Fig. 8.7 | Using arrays to eliminate a Select Case statement. (Part 4 of 4.)
2009 Pearson Education,
Inc. All rights reserved.
34
8.6 Passing an Array to a Method
• To pass an array as an argument, use the name of the
array without parentheses:
Dim hourlyTemperatures As Integer() = New Integer(24) {}
DisplayDayData(hourlyTemperatures)
• The method header for DayData might be written as:
Sub DisplayDayData(ByVal temperatureData As Integer())
2009 Pearson Education, Inc. All rights reserved.
35
Outline
PassArray.vb
1
2
' Fig. 8.11: PassArray.vb
' Passing arrays and individual array elements to methods.
3
Module PassArray
4
5
6
7
8
9
10
( 1 of 5 )
Sub Main()
Dim array1 As Integer() = New Integer() {1, 2, 3, 4, 5}
Console.WriteLine("EFFECTS OF PASSING AN ENTIRE ARRAY " & _
"BY REFERENCE:" & vbNewLine & vbNewLine & _
"The values of the original array are:")
11
' display original elements of array1
12
13
14
15
For i = 0 To array1.GetUpperBound(0)
Console.Write(" " & array1(i))
Next
16
ModifyArray(array1) ' array is passed by reference
17
18
19
Console.WriteLine(vbNewLine & _
"The values of the modified array are:")
array1 is passed by
reference to method
ModifyArray
Fig. 8.11 | Passing arrays and individual array elements
to methods. (Part 1 of 5.)
2009 Pearson Education,
Inc. All rights reserved.
36
Outline
20
21
22
' display modified elements of array1
For i = 0 To array1.GetUpperBound(0)
Console.Write("
" & array1(i))
23
24
Next
25
26
27
Console.WriteLine(vbNewLine & vbNewLine & _
"EFFECTS OF PASSING AN ARRAY ELEMENT BY VALUE:" & vbNewLine & _
vbNewLine & "array1(3) before ModifyElementByVal: " & _
28
29
30
( 2 of 5 )
array1(3))
ModifyElementByVal(array1(3)) ' array element passed by value
31
32
33
34
35
36
37
Console.WriteLine("array1(3) after ModifyElementByVal: " & _
array1(3))
Console.WriteLine(vbNewLine & "EFFECTS OF PASSING AN " & _
"ARRAY ELEMENT BY REFERENCE: " & vbNewLine & vbNewLine & _
"array1(3) before ModifyElementByRef: " & array1(3))
38
39
Console.WriteLine("array1(3) after ModifyElementByRef: " & _
array1(3))
40
PassArray.vb
ModifyElementByRef(array1(3)) ' array element passed by reference
array1(3) is passed
by value to method
ModifyElementBy
Val.
array1(3) is passed
by reference to method
ModifyElementBy
Ref.
End Sub ' Main
Fig. 8.11 | Passing arrays and individual array elements
to methods. (Part 2 of 5.)
2009 Pearson Education,
Inc. All rights reserved.
37
Outline
PassArray.vb
41
42
' method modifies array it receives (note ByVal)
43
Sub ModifyArray(ByVal arrayParameter As Integer())
44
45
For j = 0 To arrayParameter.GetUpperBound(0)
arrayParameter(j) *= 2 ' double the array element
46
47
48
Next
End Sub ' ModifyArray
49
50
51
' method modifies integer passed to it
' original is not modified (note ByVal)
Sub ModifyElementByVal(ByVal element As Integer)
52
Console.WriteLine("Value received in ModifyElementByVal: " & _
53
54
element)
element *= 2 ' double the array element
55
56
Console.WriteLine("Value calculated in ModifyElementByVal: " & _
element)
57
58
59
( 3 of 5 )
ModifyArray doubles
each element (passed by
value).
ModifyElementByVal
doubles an element passed
by value.
End Sub ' ModifyElementByVal
' method modifies integer passed to it
Fig. 8.11 | Passing arrays and individual array elements
to methods. (Part 3 of 5.)
2009 Pearson Education,
Inc. All rights reserved.
38
Outline
PassArray.vb
60
' original is modified (note ByRef)
61
62
63
Sub ModifyElementByRef(ByRef element As Integer)
Console.WriteLine("Value received in ModifyElementByRef: " & _
element)
64
65
element *= 2 ' double the array element
Console.WriteLine("Value calculated in ModifyElementByRef: " & _
66
element)
67
End Sub ' ModifyElementByRef
68 End Module ' PassArray
( 4 of 5 )
ModifyElementByRef
doubles an element passed
by reference.
EFFECTS OF PASSING AN ENTIRE ARRAY BY REFERENCE:
The values of
1 2 3 4
The values of
2 4 6 8
the original array are:
5
the modified array are:
10
(continued on next page...)
Fig. 8.11 | Passing arrays and individual array elements
to methods. (Part 4 of 5.)
2009 Pearson Education,
Inc. All rights reserved.
39
Outline
(continued from previous page…)
EFFECTS OF PASSING AN ARRAY ELEMENT BY VALUE:
PassArray.vb
array1(3) before ModifyElementByVal: 8
Value received in ModifyElementByVal: 8
Value calculated in ModifyElementByVal: 16
array1(3) after ModifyElementByVal: 8
(5 of 5 )
EFFECTS OF PASSING AN ARRAY ELEMENT BY REFERENCE:
array1(3) before ModifyElementByRef: 8
Value received in ModifyElementByRef: 8
Value calculated in ModifyElementByRef: 16
array1(3) after ModifyElementByRef: 16
Fig. 8.11 | Passing arrays and individual array elements
to methods. (Part 5 of 5.)
Common Programming Error 8.4
When passing an array to a method, including an empty pair of
parentheses after the array name is a syntax error.
2009 Pearson Education,
Inc. All rights reserved.
40
Outline
• The For Each…Next repetition statement iterates
through the values in a data structure, such as an array.
1
2
' Fig. 8.12: ForEach.vb
' Program uses For Each Next to find the minimum grade.
3
4
5
6
7
8
9
Module ForEach
Sub Main()
Dim gradeArray As Integer() = _
{77, 68, 86, 73, 98, 87, 89, 81, 70, 90, 86, 81}
Dim lowGrade As Integer = 100
' use For Each Next to find the minimum grade
10
11
For Each grade In gradeArray
If grade < lowGrade Then
12
13
14
15
lowGrade = grade
End If
Next
16
Console.WriteLine("The minimum grade is: {0}", lowGrade)
ForEach.vb
The For Each header
specifies an element
variable and the array.
Finding the minimum value
in the array.
17
End Sub ' Main
18 End Module ' ForEach
The minimum grade is: 68
Fig. 8.12 | Using For Each...Next with an array.
2009 Pearson Education,
Inc. All rights reserved.
41
Outline
GradeBook.vb
1
2
3
4
5
6
7
8
9
10
' Fig. 8.13: GradeBook.vb
' GradeBook class uses an array to store test grades.
Public Class GradeBook
Private courseNameValue As String ' name of course
Private grades As Integer() ' array of student grades
Array grades is declared
as an instance variable.
' two-argument constructor initializes courseNameValue and grades
Public Sub New(ByVal name As String, ByVal gradesArray As Integer())
CourseName = name ' initializes courseNameValue via property
grades = gradesArray ' store reference to gradesArray
End Sub ' New
11
12
13
' property CourseName
14
15
Public Property CourseName() As String
Get
16
17
18
( 1 of 7 )
Return courseNameValue
End Get
Fig. 8.13 | GradeBook class using an array to store test grades. (Part 1 of 7.)
2009 Pearson Education,
Inc. All rights reserved.
42
Outline
GradeBook.vb
19
20
21
Set(ByVal name As String)
courseNameValue = name
End Set
22
23
End Property ' Course Name
24
25
26
27
' display a welcome message to the GradeBook user
Public Sub DisplayMessage()
Console.WriteLine("Welcome to the grade book for " & vbNewLine & _
CourseName & vbNewLine)
28
End Sub ' DisplayMessage
29
30
31
' perform various operations on the data
Public Sub ProcessGrades()
32
33
34
35
36
( 2 of 7 )
OutputGrades() ' output grades array
' call method GetAverage to calculate the average grade
Console.WriteLine("Class average is {0:F2}", GetAverage())
ProcessGrades outputs
a grade report.
Fig. 8.13 | GradeBook class using an array to store test grades. (Part 2 of 7.)
2009 Pearson Education,
Inc. All rights reserved.
43
Outline
37
' call methods GetMinimum and GetMaximum
38
39
Console.WriteLine("Lowest grade is {0}", GetMinimum())
Console.WriteLine("Highest grade is {0}", GetMaximum())
GradeBook.vb
( 3 of 7 )
40
41
42
43
44
' call OutputBarChart to print grade distribution chart
OutputBarChart()
End Sub ' ProcessGrades
45
' find minimum grade
46
Public Function GetMinimum() As Integer
47
48
49
50
51
52
53
54
55
56
57
58
ProcessGrades outputs
a grade report.
Dim lowGrade As Integer = grades(0) ' assume grades(0) is smallest
' loop through grades array
For Each grade In grades
' if grade lower than lowGrade, assign it to lowGrade
If grade < lowGrade Then
lowGrade = grade ' new lowest grade
End If
Next
GetMinimum loops through
the array and compares
values to lowGrade.
Return lowGrade ' return lowest grade
End Function ' GetMinimum
Fig. 8.13 | GradeBook class using an array to store test grades. (Part 3 of 7.)
2009 Pearson Education,
Inc. All rights reserved.
44
Outline
GradeBook.vb
59
60
61
62
( 4 of 7 )
' find maximum grade
Public Function GetMaximum() As Integer
Dim highGrade As Integer = grades(0) ' assume grades(0) is largest
63
64
' loop through grades array
65
66
For Each grade In grades
' if grade greater than highGrade, assign it to highGrade
67
68
69
70
71
72
73
If grade > highGrade Then
highGrade = grade ' new highest grade
End If
Next
Return highGrade ' return highest grade
End Function ' GetMaximum
74
Fig. 8.13 | GradeBook class using an array to store test grades. (Part 4 of 7.)
2009 Pearson Education,
Inc. All rights reserved.
45
Outline
GradeBook.vb
75
76
77
78
79
' determine average grade for test
Public Function GetAverage() As Double
Dim total As Integer = 0 ' initialize total
( 5 of 7 )
' sum grades
80
81
82
83
For Each grade In grades
total += grade
Next
84
' return average of grades
85
86
87
Return (total / grades.Length)
End Function ' GetAverage
88
89
90
' output bar chart displaying grade distribution
Public Sub OutputBarChart()
Console.WriteLine(vbNewLine & "Grade distribution:")
Using a For Each
statement to total the values
in grades.
91
Fig. 8.13 | GradeBook class using an array to store test grades. (Part 5 of 7.)
2009 Pearson Education,
Inc. All rights reserved.
46
Outline
GradeBook.vb
92
93
94
' stores frequency of grades in each range of 10 grades
Dim frequency As Integer() = New Integer(10) {}
95
96
' for each grade, increment the appropriate frequency
For Each grade In grades
97
98
99
100
frequency(grade \ 10) += 1
Next
' for each grade frequency, print bar in chart
101
For count = 0 To frequency.GetUpperBound(0)
( 6 of 7 )
Counting the frequency
of each letter grade level.
102
103
104
' output bar label ( "00-09: ", ..., "90-99: ", "100: " )
If count = 10 Then
Console.Write("{0, 5:D}: ", 100)
105
106
107
Else
Console.Write("{0, 2:D2}-{1, 2:D2}: ", _
count * 10, count * 10 + 9)
108
109
End If
The format string indicates the
format D2 (two decimal digits).
Fig. 8.13 | GradeBook class using an array to store test grades. (Part 6 of 7.)
2009 Pearson Education,
Inc. All rights reserved.
47
Outline
110
' print bar of asterisks
111
112
For stars As Integer = 0 To frequency(count) - 1
Console.Write("*")
113
Next stars
114
115
116
117
GradeBook.vb
( 7 of 7 )
Console.WriteLine() ' start a new line of output
Next count
End Sub ' OutputBarChart
118
119
120
121
122
123
124
125
126
127
128
129
' output the contents of the grades array
Public Sub OutputGrades()
Console.WriteLine("The grades are:" & vbNewLine)
' output each student's grade
For student = 0 To grades.GetUpperBound(0)
Console.WriteLine("Student {0, 2:D}: {1, 3:D}", _
student + 1, grades(student))
Printing the student number
and grade for each student.
Next
Console.WriteLine()
130
End Sub ' OutputGrades
131 End Class ' GradeBook
Fig. 8.13 | GradeBook class using an array to store test grades. (Part 7 of 7.)
2009 Pearson Education,
Inc. All rights reserved.
48
Outline
GradeBookTest.vb
1
' Fig. 8.14: GradeBookTest.vb
2
3
' Create GradeBook object using any array of grades.
Module GradeBookTest
4
5
Sub Main()
' array of student grades
6
7
8
9
Dim gradesArray As Integer() = _
{87, 68, 94, 100, 83, 78, 85, 91, 76, 87}
Dim gradeBooks As New GradeBook( _
"CS101 Introduction to Visual Basic Programming", gradesArray)
10
gradeBooks.DisplayMessage()
11
12
( 1 of 3 )
Initializing gradesArray
to an array of grade values.
gradeBooks.ProcessGrades()
End Sub ' Main
13 End Module ' GradeBookTest
Fig. 8.14 | GradeBookTest creates a GradeBook object using an array of
grades, then invokes method ProcessGrades to analyze them. (Part 1 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
Welcome to the grade book for
CS101 Introduction to Visual Basic Programming
49
Outline
The grades are:
Student 1: 87
Student 2: 68
Student 3: 94
Student 4: 100
Student 5: 83
Student 6: 78
Student 7: 85
Student 8: 91
Student 9: 76
Student 10: 87
GradeBookTest.vb
( 2 of 3 )
Class average is 84.90
Lowest grade is 68
Highest grade is 100
Grade distribution:
00-09:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
100: *
Fig. 8.14 | GradeBookTest creates a GradeBook object using an array of grades,
then invokes method ProcessGrades to analyze them. (Part 2 of 2.) 2009 Pearson Education,
Inc. All rights reserved.
50
Outline
GradeBookTest.vb
( 3 of 3 )
Software Engineering Observation 8.1
A test application is responsible for creating an object
of the class being tested and providing it with data.
This data could come from any of several sources.
After passing this data to the class’s constructor to
instantiate the object, the test harness should call the
object’s methods to verify that they work properly.
2009 Pearson Education,
Inc. All rights reserved.
51
Outline
• Sorting data is one of the most popular computing
applications.
• Method Sort of class Array sorts an array’s elements
into ascending order (Fig. 8.15).
1
' Fig. 8.15: SortTest.vb
2
3
4
' Program creates random numbers and sorts them.
Public Class SortArray
Dim integerArray As Integer() = New Integer(9) {}
5
6
7
8
9
10
11
SortTest.vb
( 1 of 3 )
' creates random generated numbers
Private Sub createButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles createButton.Click
Dim output As String = String.Empty
Dim randomNumber As Random = New Random()
12
13
14
sortedTextBox.Clear() ' clear sortedTextBox
Fig. 8.15 | Sorting an array with method Array.Sort. (Part 1 of 3.)
2009 Pearson Education,
Inc. All rights reserved.
52
Outline
SortTest.vb
15
16
17
' create 10 random numbers and append to output
For i = 0 To integerArray.GetUpperBound(0)
integerArray(i) = randomNumber.Next(100)
18
19
20
output &= (integerArray(i) & vbNewLine)
Next
21
22
23
originalTextBox.Text = output ' display numbers
sortButton.Enabled = True ' enable Sort button
End Sub ' createButton_Click
24
25
' sorts randomly generated numbers
26
27
Private Sub sortButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles sortButton.Click
28
29
30
31
32
( 2 of 3 )
10 random values are
assigned to
integerArray and the
contents are displayed.
Dim output As String = String.Empty
Array.Sort(integerArray) ' sort array integerArray
array is sorted in
ascending order.
Fig. 8.15 | Sorting an array with method Array.Sort. (Part 2 of 3.)
2009 Pearson Education,
Inc. All rights reserved.
53
Outline
33
' creates string with sorted numbers
34
35
36
For i = 0 To integerArray.GetUpperBound(0)
output &= (integerArray(i) & vbNewLine)
Next
37
SortTest.vb
( 3 of 3 )
38
sortedTextBox.Text = output ' display numbers
39
40
41
sortButton.Enabled = False ' disable Sort button
createButton.Focus() ' set focus to createButton
End Sub ' sortButton_Click
42 End Class ' SortTest
a)
b)
Fig. 8.15 | Sorting an array with method Array.Sort. (Part 3 of 3.)
2009 Pearson Education,
Inc. All rights reserved.
54
Outline
LinearSearch.vb
1
' Fig. 8.16: LinearSearch.vb
2
' Linear search of an array.
3
Module LinearSearch
4
5
6
7
8
9
10
11
' iterates through array
Function Search(ByVal key As Integer, _
ByVal numbers As Integer()) As Integer
' statement iterates linearly through array
For i = 0 To numbers.GetUpperBound(0)
If numbers(i) = key Then
Return i
12
13
End If
Next
14
15
Return -1 ' indicates the key was not found
Search compares each
element of an array with a
search key.
16
End Function ' Search
17 End Module ' LinearSearch
Fig. 8.16 | Method for performing a linear search.
2009 Pearson Education,
Inc. All rights reserved.
55
Outline
1
' Fig. 8.17: LinearSearchTest.vb
2
' Linear search of an array.
3
Public Class LinearSearchTest
4
5
Dim array1 As Integer() = New Integer(19) {}
6
7
8
' create random data
Private Sub createButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles createButton.Click
9
10
Dim randomNumber As Random = New Random()
11
Dim output As String = ("Index" & vbTab & "Value" & vbNewLine)
12
13
14
15
' create string containing 20 random numbers
For i = 0 To array1.GetUpperBound(0)
array1(i) = randomNumber.Next(1000)
16
17
18
output &= (i & vbTab & array1(i) & vbNewLine)
Next
19
20
dataTextBox.Text = output ' display numbers
inputTextBox.Clear() ' clear search key text box
21
searchButton.Enabled = True ' enable search button
22
LinearSearchTest
.vb
( 1 of 3 )
End Sub ' createButton_Click
Fig. 8.17 | Linear search of an array. (Part 1 of 3.)
2009 Pearson Education,
Inc. All rights reserved.
56
Outline
23
24
' search array for search key
25
Private Sub searchButton_Click(ByVal sender As System.Object, _
26
27
ByVal e As System.EventArgs) Handles searchButton.Click
28
' if search key text box is empty, display
29
30
' message and exit method
If String.IsNullOrEmpty(inputTextBox.Text) Then
31
32
33
34
LinearSearchTest
.vb
( 2 of 3 )
MessageBox.Show("You must enter a search key.", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
35
36
Dim searchKey As Integer = Convert.ToInt32(inputTextBox.Text)
37
Dim element As Integer = LinearSearch.Search(searchKey, array1)
38
39
If element <> -1 Then
40
resultLabel.Text = "Found value in index " & element
41
Else
42
resultLabel.Text = "Value not found"
43
End If
44
End Sub ' searchButton_Click
45 End Class ' LinearSearchTest
Storing element as the
result of a linear search.
Fig. 8.17 | Linear search of an array. (Part 2 of 3.)
2009 Pearson Education,
Inc. All rights reserved.
57
Outline
LinearSearchTest
.vb
( 3 of 3 )
Fig. 8.17 | Linear search of an array. (Part 3 of 3.)
2009 Pearson Education,
Inc. All rights reserved.
58
• If an array is sorted, the high-speed binary
search technique can be used.
Outline
• Figure 8.18 uses method BinarySearch of class
Array
BinarySearchTest
.vb
1
2
3
4
5
6
7
8
9
10
' Fig. 8.18: BinarySearchTest.vb
' Binary search of an array using Array.BinarySearch.
Public Class BinarySearchTest
Dim array1 As Integer() = New Integer(19) {}
' create random data
Private Sub createButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles createButton.Click
Dim randomNumber As Random = New Random()
11
Dim output As String = ("Index" & vbTab & "Value" & vbNewLine)
12
13
14
' create random array elements
For i As Integer = 0 To array1.GetUpperBound(0)
15
16
17
18
( 1 of 4 )
Sort must be
invoked before
passing the array.
array1(i) = randomNumber.Next(1000)
Next
Array.Sort(array1) ' sort array to enable binary searching
19
Fig. 8.18 | Binary search of an array. (Part 1 of 4.)
2009 Pearson Education,
Inc. All rights reserved.
59
Outline
20
' display sorted array elements
21
22
23
For i As Integer = 0 To array1.GetUpperBound(0)
output &= (i & vbTab & array1(i) & vbNewLine)
Next
BinarySearchTest
.vb
( 2 of 4 )
24
25
26
27
28
29
dataTextBox.Text = output ' displays numbers
inputTextBox.Clear() ' clear search key text box
searchButton.Enabled = True ' enable search button
End Sub ' createButton_Click
30
31
32
' search array for search key
Private Sub searchButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles searchButton.Click
33
34
35
' if search key text box is empty, display
' message and exit method
36
37
38
39
40
If String.IsNullOrEmpty(inputTextBox.Text) Then
MessageBox.Show("You must enter a search key.", "Error", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Fig. 8.18 | Binary search of an array. (Part 2 of 4.)
2009 Pearson Education,
Inc. All rights reserved.
60
Outline
BinarySearchTest
.vb
41
42
43
Dim searchKey As Integer = Convert.ToInt32(inputTextBox.Text)
Dim element As Integer = Array.BinarySearch(array1, searchKey)
44
45
If element >= 0 Then
46
47
48
49
resultLabel.Text = "Found Value in index " & element
Else
resultLabel.Text = "Value Not Found"
End If
50
End Sub ' searchButton_Click
51 End Class ' BinarySearchTest
( 3 of 4 )
The search key is converted
to an integer.
Storing element as the
result of a linear search.
Displaying the search
result.
Fig. 8.18 | Binary search of an array. (Part 3 of 4.)
2009 Pearson Education,
Inc. All rights reserved.
61
Outline
BinarySearchTest
.vb
( 4 of 4 )
Fig. 8.18 | Binary search of an array. (Part 4 of 4.)
2009 Pearson Education,
Inc. All rights reserved.
62
8.11 Rectangular Arrays
• Rectangular arrays represent tables of values in rows and columns.
• Figure 8.19 illustrates a 3-by-4 array.
Fig. 8.19 | Two-dimensional array with three rows and four columns.
2009 Pearson Education, Inc. All rights reserved.
63
8.11 Rectangular Arrays (Cont.)
• A two-dimensional rectangular array can be declared
and initialized like this:
Dim numbers As Integer(,) = New Integer(1,1) {}
numbers(0, 0) = 1 ' leftmost element in row 0
numbers(0, 1) = 2 ' rightmost element in row 0
numbers(1, 0) = 3 ' leftmost element in row 1
numbers(1, 1) = 4 ' rightmost element in row 1
2009 Pearson Education, Inc. All rights reserved.
64
8.11 Rectangular Arrays (Cont.)
• The initialization can also be written on one line:
Dim numbers As Integer(,) = New Integer(,) {{1, 2}, {3, 4}}
• The preceding declaration can also be written as
Dim numbers As Integer(,) = {{1, 2}, {3, 4}}
2009 Pearson Education, Inc. All rights reserved.
65
Outline
• The program in Fig. 8.20 demonstrates the initialization
of a rectangular array and the use of nested
For Next loop.
1
' Fig. 8.20: RectangularArray.vb
2
' Initializing a rectangular array.
3
4
Module RectangularArray
Sub Main()
5
' create rectangular array
6
7
8
Dim array1 As Integer(,)
array1 = New Integer(,) {{1, 2, 3}, {4, 5, 6}}
9
10
Console.WriteLine("Values in rectangular array1 by row are ")
RectangularArray
.vb
( 1 of 2 )
Initializing array1 to a
rectangular array
Fig. 8.20 | Initializing a rectangular array. (Part 1 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
66
Outline
RectangularArray
.vb
11
12
13
14
15
( 2 of 2 )
' output array1 elements
For i = 0 To array1.GetUpperBound(0)
For j = 0 To array1.GetUpperBound(1)
Console.Write(array1(i, j) & " ")
Next j
The inner For…Next statement
traverses the columns within a row.
16
17
18
19
Console.WriteLine()
Next i
End Sub ' Main
The outer For…Next
statement traverses the rows
20 End Module ' RectangularArray
Values in rectangular array1 by row are
1 2 3
4 5 6
Fig. 8.20 | Initializing a rectangular array. (Part 2 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
67
• Figure 8.21 contains a version of class GradeBook
that uses a rectangular array.
• Method OutputBarChart uses nested loops to
produce a bar chart of student grades.
1
' Fig. 8.21: GradeBook.vb
2
' Grade book using a rectangular array to store grades.
3
4
5
Public Class GradeBook
Private courseNameValue As String ' name of course
Private grades As Integer(,) ' rectangular array of student grades
6
7
8
9
10
11
Outline
GradeBook.vb
(1 of 8 )
Initializing grades to a
rectangular array
' two-argument constructor initializes courseNameValue and Grades
Public Sub New(ByVal name As String, ByVal gradesArray As Integer(,))
CourseName = name ' initializes courseNameValue via property
grades = gradesArray ' store grades
End Sub ' New
Setting grades to a
rectangular array
12
13
14
' property CourseName
Public Property CourseName() As String
15
Get
16
17
Return courseNameValue
End Get
18
Fig. 8.21 | GradeBook class using a rectangular array to
store grades. (Part 1 of 8.)
2009 Pearson Education,
Inc. All rights reserved.
68
Outline
19
Set(ByVal name As String)
20
21
22
courseNameValue = name
End Set
End Property ' CourseName
23
24
' display a welcome message to the GradeBook user
25
26
27
28
Public Sub DisplayMessage()
Console.WriteLine("Welcome to the grade book for " & vbNewLine & _
CourseName & vbNewLine)
End Sub ' DisplayMessage
29
30
31
' perform various operations on the data
Public Sub ProcessGrades()
32
OutputGrades() ' output grades array
33
34
' call methods GetMinimum and GetMaximum
35
36
37
38
Console.WriteLine("Lowest grade in the grade book is {0}", _
GetMinimum())
Console.WriteLine("Highest grade in the grade book is {0}", _
GetMaximum())
GradeBook.vb
( 2 of 8 )
Fig. 8.21 | GradeBook class using a rectangular array to
store grades. (Part 2 of 8.)
2009 Pearson Education,
Inc. All rights reserved.
69
Outline
39
40
' call OutputBarChart to print grade distribution chart
41
OutputBarChart()
42
43
End Sub ' ProcessGrades
44
45
46
' find minimum grade
Public Function GetMinimum() As Integer
' assume first element of grades array is smallest
47
48
49
Dim lowGrade As Integer = grades(0,0)
50
51
52
53
54
55
56
For i = 0 To grades.GetUpperBound(0)
' loop through columns of current row
For j = 0 To grades.GetUpperBound(1)
' if grade lower than lowGrade, assign it to lowGrade
If grades(i,j) < lowGrade Then
lowGrade = grades(i,j) ' new lowest grade
End If
57
58
59
Next j
Next i
GradeBook.vb
( 3 of 8 )
' loop through grades array
GetMinimum determines
the lowest grade of any
student.
Fig. 8.21 | GradeBook class using a rectangular array to
store grades. (Part 3 of 8.)
2009 Pearson Education,
Inc. All rights reserved.
70
Outline
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
Return lowGrade ' return lowest grade
End Function ' GetMinimum
' find maximum grade
Public Function GetMaximum() As Integer
' assume first element of grades array is largest
Dim highGrade As Integer = grades(0,0)
GradeBook.vb
( 4 of 8 )
GetMinimum determines
the lowest grade of any
student.
' loop through grades array
For i = 0 To grades.GetUpperBound(0)
' loop through columns of current row
For j = 0 To grades.GetUpperBound(1)
' if grade greater than highGrade, assign it to highGrade
If grades(i,j) > highGrade Then
highGrade = grades(i,j) ' new highest grade
End If
GetMaximum determines
the highest grade of any
student.
Next j
Next i
Return highGrade ' return highest grade
End Function ' GetMaximum
Fig. 8.21 | GradeBook class using a rectangular array to
store grades. (Part 4 of 8.)
2009 Pearson Education,
Inc. All rights reserved.
71
Outline
81
82
83
84
85
86
87
88
89
90
91
92
93
GradeBook.vb
' determine average grade for particular student’s grades
Public Function GetAverage(ByVal row As Integer) As Double
Dim total As Integer = 0 ' initialize total
' sum grades for one student
For column = 0 To grades.GetUpperBound(1)
total += grades(row, column)
Next
( 5 of 8 )
GetAverage determines
a particular student’s
average.
' return average of grades
Return (total / (grades.GetUpperBound(1) + 1))
End Function ' GetAverage
94
95
96
97
98
99
100
' output bar chart displaying grade distribution
Public Sub OutputBarChart()
Console.WriteLine(vbNewLine & "Overall grade distribution:")
' stores frequency of grades in each range of 10 grades
Dim frequency As Integer() = New Integer(10) {}
Fig. 8.21 | GradeBook class using a rectangular array to
store grades. (Part 5 of 8.)
2009 Pearson Education,
Inc. All rights reserved.
72
Outline
GradeBook.vb
101
102
103
104
105
( 6 of 8 )
' for each grade, increment the appropriate frequency
For i = 0 To grades.GetUpperBound(0)
For j = 0 To grades.GetUpperBound(1)
frequency(grades(i,j) \ 10) += 1
Next j
Next i
106
107
108
109
' for each grade frequency, print bar in chart
110
For count = 0 To frequency.GetUpperBound(0)
Nested loops output a bar
chart of student grades.
111
112
113
' output bar label ( "00-09: ", ..., "90-99: ", "100: " )
If count = 10 Then
Console.Write("{0, 5:D}: ", 100)
114
115
116
Else
Console.Write("{0, 2:D2}-{1, 2:D2}: ", _
count * 10, count * 10 + 9)
117
118
End If
Fig. 8.21 | GradeBook class using a rectangular array to
store grades. (Part 6 of 8.)
2009 Pearson Education,
Inc. All rights reserved.
73
Outline
119
' print bar of asterisks
120
For stars = 0 To frequency(count) - 1
121
122
Console.Write("*")
Next stars
123
124
125
126
Console.WriteLine() ' start a new line of output
Next count
End Sub ' OutputBarChart
127
128
' output the contents of the grades array
129
130
131
Public Sub OutputGrades()
Console.WriteLine("The grades are:" & vbNewLine)
Console.Write("
") ' align column heads
132
133
134
135
136
137
' create a column heading for each of the tests
For test = 0 To grades.GetUpperBound(1)
Console.Write("Test {0:D} ", test + 1)
GradeBook.vb
( 7 of 8 )
OutputGrades outputs
the array in a tabular
format.
Next
Fig. 8.21 | GradeBook class using a rectangular array to
store grades. (Part 7 of 8.)
2009 Pearson Education,
Inc. All rights reserved.
74
Outline
138
Console.WriteLine("Average") ' student average column heading
GradeBook.vb
139
140
141
' create rows/columns of text representing array grades
For student = 0 To grades.GetUpperBound(0)
( 8 of 8 )
142
143
Console.Write("Student {0, 2:D}", student + 1)
144
145
146
147
' output student's grades
For counter = 0 To grades.GetUpperBound(1)
Console.Write("{0, 8:D}", grades(student, counter))
Next counter
148
149
150
' call method GetAverage to calculate student's average grade;
' pass row of grades as the argument to GetAverage
151
Dim average As Double = GetAverage(student)
152
153
OutputGrades outputs
the array in a tabular
format.
Console.WriteLine("{0, 9:F2}", average)
Next student
154
155
Console.WriteLine()
156
End Sub ' OutputGrades
157 End Class ' GradeBook
Fig. 8.21 | GradeBook class using a rectangular array to
store grades. (Part 8 of 8.)
2009 Pearson Education,
Inc. All rights reserved.
75
Outline
GradeBookTest.vb
1
2
' Fig. 8.22: GradeBookTest.vb
' Create GradeBook object using a rectangular array of grades.
3
4
Module GradeBookTest
Sub Main()
5
' array of student grades
6
7
8
9
Dim gradesArray As Integer(,)
gradesArray = New Integer(,) {{87, 96, 70}, {68, 87, 90}, _
{94, 37, 90}, {100, 81, 82}, {83, 65, 85}, {78, 87, 65}, _
{85, 75, 83}, {91, 59, 100}, {76, 72, 84}, {87, 93, 73}}
10
11
12
13
14
15
Dim gradeBooks As New GradeBook( _
"CS101 Introduction to Visual Basic Programming", gradesArray)
gradeBooks.DisplayMessage()
gradeBooks.ProcessGrades()
End Sub ' Main
( 1 of 2 )
gradesArray is
initialized to a rectangular
array of Integers.
A GradeBook object is
constructed from a name
String and the grades
array.
16 End Module ' GradeBookTest
Welcome to the grade book for
CS101 Introduction to Visual Basic Programming
Fig. 8.22 | Creates GradeBook object using a rectangular array of grades, then
invokes method processGrades to analyze them. (Part 1 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
76
The grades are:
Student 1
Student 2
Student 3
Student 4
Student 5
Student 6
Student 7
Student 8
Student 9
Student 10
Test 1
87
68
94
100
83
78
85
91
76
87
Outline
Test 2
96
87
37
81
65
87
75
59
72
93
Test 3
70
90
90
82
85
65
83
100
84
73
Average
84.33
81.67
73.67
87.67
77.67
76.67
81.00
83.33
77.33
84.33
GradeBookTest.vb
( 2 of 2 )
Lowest grade in the grade book is 37
Highest grade in the grade book is 100
Overall grade distribution:
00-09:
10-19:
20-29:
30-39: *
40-49:
50-59: *
60-69: ***
70-79: ******
80-89: ***********
90-99: ******
100: **
Fig. 8.22 | Creates GradeBook object using a rectangular array of grades, then
invokes method processGrades to analyze them. (Part 2 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
77
Outline
• It’s possible to create methods that receive a
variable number of arguments, using keyword
ParamArray.
ParamArrayTest.vb
( 1 of 3 )
• Figure 8.23 calls method AnyNumberOfArguments
three times, passing a different number of values each time.
1
' Fig. 8.23: ParamArrayTest.vb
2
' Using ParamArray to create variable-length parameter lists.
3
4
Module ParamArrayTest
Sub Main()
5
6
7
8
AnyNumberOfArguments()
AnyNumberOfArguments(2, 3)
AnyNumberOfArguments(7, 8, 9, 10, 11, 12)
End Sub ' Main
A different number of
arguments is used in each
call.
9
Fig. 8.23 | Creating variable-length parameter lists. (Part 1 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
78
Outline
10
' receives any number of arguments in array
11
12
13
14
Sub AnyNumberOfArguments(ByVal ParamArray array1 As Integer())
Dim total As Integer = 0
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
ParamArrayTest.vb
' check number of arguments
If array1.Length = 0 Then
Console.WriteLine("Method AnyNumberOfArguments" & _
" received 0 arguments.")
Else
Console.Write("The total of ")
' total array elements
For i = 0 To array1.GetUpperBound(0)
Console.Write(array1(i) & " ")
total += array1(i)
Next
( 2 of 3 )
Determining whether the
number of arguments is
zero.
Printing any arguments
passed to the method.
Console.WriteLine("is {0}.", total)
End If
End Sub ' AnyNumberOfArguments
30 End Module ' ParamArrayTest
Method AnyNumberOfArguments received 0 arguments.
The total of 2 3 is 5.
The total of 7 8 9 10 11 12 is 57.
Fig. 8.23 | Creating variable-length parameter lists. (Part 2 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
79
Outline
ParamArrayTest.vb
( 3 of 3 )
Common Programming Error 8.5
Attempting to declare a parameter variable to the right
of the ParamArray array variable is a syntax error.
Common Programming Error 8.6
Using ByRef with ParamArray is a syntax error.
2009 Pearson Education,
Inc. All rights reserved.
80
Outline
• Jagged arrays are maintained as arrays of arrays.
• The program in Fig. 8.24 demonstrates the use of a
jagged array.
1
' Fig. 8.24: JaggedArray.vb
2
' Initializing a jagged array.
3
4
Module JaggedArray
Sub Main()
5
' create jagged array
6
7
8
Dim array1 As Integer()() = New Integer(2)() {} ' three rows
array1(0) = New Integer() {1, 2} ' row 0 is a single array
array1(1) = New Integer() {3} ' row 1 is a single array
9
10
array1(2) = New Integer() {4, 5, 6} ' row 2 is a single array
JaggedArray.vb
( 1 of 2 )
The declaration of array1
creates a jagged array of
three arrays.
Fig. 8.24 | Initializing a jagged array. (Part 1 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
81
Outline
JaggedArray.vb
11
12
Console.WriteLine("Values in jagged array1 by row are ")
13
14
15
' output array1 elements
For i = 0 To array1.GetUpperBound(0)
For j = 0 To array1(i).GetUpperBound(0)
16
17
18
Console.Write(array1(i)(j) & "
Next
")
( 2 of 2 )
The nested For statements
traverse the jagged array.
19
Console.WriteLine()
20
Next
21
End Sub ' Main
22 End Module ' JaggedArray
Values in jagged array1 by row are
1 2
3
4 5 6
Fig. 8.24 | Initializing a jagged array. (Part 2 of 2.)
2009 Pearson Education,
Inc. All rights reserved.
82
Outline
• The ReDim statement enables you to change the
array size (Fig. 8.25).
• To save the original data stored in an array, follow
ReDim with Preserve.
1
' Fig. 8.25: ReDimTest.vb
2
3
' Resize an array using the ReDim statement.
Module ReDimTest
4
5
6
ReDimTest.vb
( 1 of 3 )
Sub Main()
' create and initialize a 5-element array
Dim array As Integer() = {1, 2, 3, 4, 5}
7
8
Dim arrayCopy As Integer() = array
9
10
' display array length and the elements in array
Console.Write("The original array has {0} elements: ", _
11
12
array.Length)
DisplayArray(array)
13
14
15
16
' change the size of the array without the Preserve keyword
ReDim array(6)
The ReDim statement
changes the upper bound of
the array.
Fig. 8.25 | Using ReDim statements to change the array size. (Part 1 of 3.)
2009 Pearson Education,
Inc. All rights reserved.
83
Outline
ReDimTest.vb
17
' display new array length and the elements in array
18
Console.Write("New array (without Preserve) has {0} elements: ", _
19
20
array.Length)
DisplayArray(array)
21
22
' change the size of the array with the Preserve keyword
23
24
25
26
27
28
29
30
31
ReDim Preserve arrayCopy(6)
arrayCopy(6) = 7 ' assign 7 to array element 6
( 2 of 3 )
Preserve indicates the
existing array elements are
kept when the array is
resized.
' display new array length and the elements in array
Console.Write("New array (with Preserve) has {0} elements: ", _
arrayCopy.Length)
DisplayArray(arrayCopy)
End Sub ' Main
Fig. 8.25 | Using ReDim statements to change the array size. (Part 2 of 3.)
2009 Pearson Education,
Inc. All rights reserved.
84
Outline
ReDimTest.vb
32
33
' display array elements
Sub DisplayArray(ByVal array As Integer())
34
For Each number In array
35
36
37
38
39
Console.Write("{0} ", number)
Next
( 3 of 3 )
Console.WriteLine()
End Sub ' DisplayArray
40 End Module ' ReDimTest
The original array has 5 elements: 1 2 3 4 5
New array (without Preserve) has 7 elements: 0 0 0 0 0 0 0
New array (with Preserve) has 7 elements: 1 2 3 4 5 0 7
Fig. 8.25 | Using ReDim statements to change the array size. (Part 3 of 3.)
2009 Pearson Education,
Inc. All rights reserved.
85
8.16 Passing Arrays: ByVal vs. ByRef
• Reference types passed via keyword ByVal are actually
passed by reference, meaning that changes are made to the
original objects.
• When a reference-type object is passed with ByRef, the
method gains control over the reference in the caller.
Performance Tip 8.1
Passing arrays and other objects by reference makes sense for
performance reasons. If arrays were passed by value, a copy of
each element would be passed. For large, frequently passed arrays,
this would waste time and consume considerable storage for the
copies of the arrays—both of these problems cause poor
performance.
2009 Pearson Education, Inc. All rights reserved.
86
Outline
• The program in Fig. 8.26 demonstrates the difference
between passing a reference ByVal and ByRef.
ArrayReferenceTest
.vb
1
' Fig. 8.26: ArrayReferenceTest.vb
2
3
4
' Testing the effects of passing array references using ByVal and ByRef.
Module ArrayReferenceTest
Sub Main()
5
6
' declare array references
Dim firstArray As Integer()
7
8
Dim firstArrayCopy As Integer()
9
10
' allocate firstArray and copy its reference
firstArray = New Integer() {1, 2, 3}
11
12
13
firstArrayCopy = firstArray ' reference preceding array
14
15
Console.Write("Contents of firstArray before calling FirstDouble: ")
16
' print contents of firstArray
17
18
For i = 0 To firstArray.GetUpperBound(0)
Console.Write(firstArray(i) & " ")
19
20
Next
( 1 of 6 )
firstArrayCopy now
refers to the same object as
firstArray.
Console.WriteLine("Passing an array reference using ByVal.")
The For statement prints the
contents of firstArray.
Fig. 8.26 | Passing an array reference with ByVal and ByRef. (Part 1 of 6.)
2009 Pearson Education,
Inc. All rights reserved.
87
Outline
ArrayReferenceTest
.vb
21
FirstDouble(firstArray) ' pass firstArray using ByVal
22
23
24
Console.Write(vbNewLine & "Contents of firstArray after " & _
"calling FirstDouble: ")
25
26
' print contents of firstArray
For i = 0 To firstArray.GetUpperBound(0)
27
28
29
30
Console.Write(firstArray(i) & " ")
Next
' was reference to firstArray changed by FirstDouble?
31
32
33
If firstArray Is firstArrayCopy Then
Console.WriteLine(vbNewLine & "The references are equal.")
Else
34
( 2 of 6 )
Console.WriteLine(vbNewLine & "The references are not equal.")
35
36
End If
37
38
39
40
' declare array references
Dim secondArray As Integer()
Dim secondArrayCopy As Integer()
Fig. 8.26 | Passing an array reference with ByVal and ByRef. (Part 2 of 6.)
2009 Pearson Education,
Inc. All rights reserved.
88
Outline
ArrayReferenceTest
.vb
41
' allocate secondArray and copy its reference
42
43
44
secondArray = New Integer() {1, 2, 3}
secondArrayCopy = secondArray
45
46
Console.WriteLine(vbNewLine & "Passing an array " & _
"reference using ByRef.")
47
48
Console.Write("Contents of secondArray before " & _
"calling SecondDouble: ")
49
50
51
' print contents of secondArray before method call
For i = 0 To secondArray.GetUpperBound(0)
52
53
54
Console.Write(secondArray(i) & " ")
Next
55
SecondDouble(secondArray) ' pass secondArray using ByRef
56
57
Console.Write(vbNewLine & "Contents of secondArray " & _
"after calling SecondDouble: ")
( 3 of 6 )
58
Fig. 8.26 | Passing an array reference with ByVal and ByRef. (Part 3 of 6.)
2009 Pearson Education,
Inc. All rights reserved.
89
Outline
ArrayReferenceTest
.vb
59
' print contents of secondArray after method call
60
61
62
For i = 0 To secondArray.GetUpperBound(0)
Console.Write(secondArray(i) & " ")
Next
63
64
65
66
67
' was reference secondArray changed by SecondDouble
If secondArray Is secondArrayCopy Then
Console.WriteLine(vbNewLine & "The references are equal.")
Else
68
69
70
( 4 of 6 )
Console.WriteLine(vbNewLine & "The references are not equal.")
End If
End Sub ' Main
71
72
73
74
75
76
77
78
' method modifies elements of array and assigns
' new reference (note ByVal)
Sub FirstDouble(ByVal array As Integer())
' double each element value in caller’s array
For i = 0 To array.GetUpperBound(0)
array(i) *= 2 ' double the ith element
Next
The For statement prints the
contents of firstArray.
Fig. 8.26 | Passing an array reference with ByVal and ByRef. (Part 4 of 6.)
2009 Pearson Education,
Inc. All rights reserved.
90
Outline
ArrayReferenceTest
.vb
79
80
' create a new array and assign its reference to the variable array
81
82
array = New Integer() {11, 12, 13}
End Sub ' FirstDouble
83
84
85
86
87
' method modifies elements of array and assigns
' new reference (note ByRef)
Sub SecondDouble(ByRef array As Integer())
' double each element value in caller’s array
88
For i = 0 To array.GetUpperBound(0)
89
90
array(i) *= 2 ' double the ith element
Next
91
92
93
94
( 5 of 6 )
FirstDouble multiplies
the values of all the
elements in the array by 2.
SecondDouble receives
its array argument ByRef.
' create a new array and assign its reference to the variable array
array = New Integer() {11, 12, 13} ' lose the 2, 4, 6 array
End Sub ' SecondDouble
95 End Module ' ArrayReferenceTest
Fig. 8.26 | Passing an array reference with ByVal and ByRef. (Part 5 of 6.)
2009 Pearson Education,
Inc. All rights reserved.
91
Outline
Passing an array reference using ByVal.
Contents of firstArray before calling FirstDouble: 1 2 3
Contents of firstArray after calling FirstDouble: 2 4 6
The references are equal.
Passing an array reference using ByRef.
Contents of secondArray before calling SecondDouble: 1 2 3
Contents of secondArray after calling SecondDouble: 11 12 13
The references are not equal.
ArrayReferenceTest
.vb
( 6 of 6 )
Fig. 8.26 | Passing an array reference with ByVal and ByRef. (Part 6 of 6.)
Software Engineering Observation 8.2
Using ByVal to receive a reference-type object parameter does not
cause the object to pass by value. ByVal causes only the object’s
reference to pass by value. This prevents a called method from
overwriting a reference in the caller. In the vast majority of cases,
protecting the caller’s reference from modification is the desired
behavior.
2009 Pearson Education,
Inc. All rights reserved.
© Copyright 2026 Paperzz