85
2009 Pearson Education, Inc. All rights rese 1 8 Arrays

2009 Pearson Education, Inc. All rights reserved. 1 8 8 Arrays

Embed Size (px)

Citation preview

2009 Pearson Education, Inc. All rights reserved.

1

88

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 ontill 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 Repetition Statement

8.8 GradeBook 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

Fig. 8.1 | Array consisting of 12 elements.

8.2  Arrays (Cont.)• Figure 8.1 shows a representation of an integer array called c.

2009 Pearson Education, Inc. All rights reserved.

10

Common Programming Error 8.1Array 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.”

8.2  Arrays (Cont.)

2009 Pearson Education, Inc. All rights reserved.

11

• 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)

8.2  Arrays (Cont.)

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.2Explicitly setting the lower bound of an array to a value otherthan 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

1 ' Fig. 8.2: CreateArray.vb

2 ' Declaring and allocating an array.

3 Module CreateArray

4 Sub Main()

5 Dim array As Integer() ' declare array variable

6

7 ' allocate memory for 10-element array using explicit array bounds

8 array = New Integer(0 To 9) {}

9

10 Console.WriteLine("Index " & vbTab & "Value")

11

12 ' display values in array

13 For i = 0 To array.GetUpperBound(0)

14 Console.WriteLine(i & vbTab & array(i))

15 Next

16

17 Console.WriteLine(vbNewLine & "The array contains " & _

18 array.Length & " elements.")

19 End Sub ' Main

20 End Module ' CreateArray

Outline

CreateArray.vb

( 1 of 2 )

Outline

• The program in Fig. 8.2 uses the New operator to allocatean array of 10 Integer elements.

array can reference an array of Integers.

Initializing array to an array of Integers.

Length returns the number of elements in the array.

The For statement displays the index and value of each element.

Fig. 8.2 | Creating an array. (Part 1 of 2.)

2009 Pearson Education, Inc. All rights reserved.

15

Index Value 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 The array contains 10 elements.

Outline

CreateArray.vb

( 2 of 2 )

Fig. 8.2 | Creating an array. (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

16

1 ' Fig. 8.3: InitArray.vb

2 ' Initializing arrays.

3 Module InitArray

4 Sub Main()

5 ' initializer list specifies the number of elements

6 ' and the value of each element

7 Dim array1 As Integer() = _

8 {32, 27, 64, 18, 95, 14, 90, 70, 60, 37}

9

10 ' allocate array2 based on length of array1

11 Dim array2 As Integer() = New Integer(array1.GetUpperBound(0)) {}

12

13 ' set values in array2 by a calculation

14 For i = 0 To array2.GetUpperBound(0)

15 array2(i) = 2 + 2 * i ' generate 2, 4, 6, ..., 20

16 Next

17

18 Console.WriteLine("Index " & vbTab & "Array1" & vbTab & "Array2")

19

Outline

InitArray.vb

( 1 of 2 )

• Figure 8.3 creates two 10-element integer arrays and sets their element values.

array1 is initialized to a new array.

array2 is initialized to be the same length as array1.

Initializing the elements in array2 to even integers 2-20.

Fig. 8.3 | Initializing array elements with an array initializerand a For statement. (Part 1 of 2.)

2009 Pearson Education, Inc. All rights reserved.

17

20 ' display values for both arrays side by side

21 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 Array1 Array2 0 32 2 1 27 4 2 64 6 3 18 8 4 95 10 5 14 12 6 90 14 7 70 16 8 60 18 9 37 20

Outline

InitArray.vb

( 2 of 2 )

Fig. 8.3 | Initializing array elements with an array initializerand a For statement. (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

18

1 ' Fig. 8.4: SumArray.vb

2 ' Computing the sum of the elements in an array.

3 Module SumArray

4 Sub Main()

5 Dim array As Integer() = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

6 Dim total As Integer = 0

7

8 ' sum the array element values

9 For i = 0 To array.GetUpperBound(0)

10 total += array(i)

11 Next

12

13 Console.WriteLine("Total of array elements: {0}", total)

14 End Sub ' Main

15 End Module ' SumArray Total of array elements: 55

Outline

SumArray.vb

array is initialized to an array of Integers.

The For... statement sums the elements of array.

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

1 ' Fig. 8.5: StudentPoll.vb

2 ' Using arrays to display poll results.

3 Module StudentPoll

4 Sub Main()

5 ' student response array (more typically, input at run time)

6 Dim responses As Integer() = _

7 {1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, _

8 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10}

9

10 ' response frequency array (indices 0 through 10)

11 Dim frequency As Integer() = New Integer(10) {}

12

13 ' count frequencies

14 For answer = 0 To responses.GetUpperBound(0)

15 frequency(responses(answer)) += 1

16 Next

17

18 Console.WriteLine("Rating " & vbTab & "Frequency ")

19

20 ' display output, ignore element 0 of frequency

21 For rating = 1 To frequency.GetUpperBound(0)

22 Console.WriteLine(rating & vbTab & frequency(rating))

23 Next

24 End Sub ' Main

25 End Module ' StudentPoll

Outline

StudentPoll.vb

( 1 of 2 )

• This is a typical array-processing application (Fig. 8.5).

The For statement iterates through responses and increments frequency.

Fig. 8.5 | Simple student-poll analysis program. (Part 1 of 2.)

2009 Pearson Education, Inc. All rights reserved.

21

Rating Frequency 1 2 2 2 3 2 4 2 5 5 6 11 7 5 8 7 9 1 10 3

Outline

StudentPoll.vb

( 2 of 2 )

Common Programming Error 8.3When 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.1When looping through an array, the array index should remainbetween 0 and the upper bound of the array.

Fig. 8.5 | Simple student-poll analysis program. (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

22

1 ' Fig. 8.6: BarChart.vb

2 ' Using data to create bar chart.

3 Module BarChart

4 Sub Main()

5 ' create data array

6 Dim array1 As Integer() = {19, 3, 15, 7, 11, 9, 13, 5, 17, 1}

7

8 Console.WriteLIne("Element " & "Value " & vbTab & "Bar Chart")

9

10 ' display a bar of the bar chart for each element in the array

11 For i = 0 To array1.GetUpperBound(0)

12 Console.Write(i & vbTab & array1(i) & vbTab)

13

14 For j = 1 To array1(i)

15 Console.Write("*") ' display one asterisk

16 Next j

17

18 Console.WriteLine()

19 Next i

20 End Sub ' Main

21 End Module ' BarChart

Outline

BarChart.vb

( 1 of 2 )

• Figure 8.6 displays data by creating a bar chartwith asterisks (*).

Writing asterisks representing the value of each element.

Fig. 8.6 | Bar chart printing program. (Part 1 of 2.)

2009 Pearson Education, Inc. All rights reserved.

23

Element Value Bar Chart 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *

Outline

BarChart.vb

( 2 of 2 )

Fig. 8.6 | Bar chart printing program. (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

24

1 ' Fig. 8.7: RollDie.vb

2 ' Rolling 12 dice with frequency chart.

3 Public Class RollDie

4 Dim randomNumber As Random = New Random()

5 Dim frequency As Integer() = New Integer(6) {}

6

7 ' event handler for rollButton's Click event

8 Private Sub rollButton_Click(ByVal sender As System.Object, _

9 ByVal e As System.EventArgs) Handles rollButton.Click

10

11 ' pass PictureBox to a method that assigns a face to each die

12 DisplayDie(die1PictureBox)

13 DisplayDie(die2PictureBox)

14 DisplayDie(die3PictureBox)

15 DisplayDie(die4PictureBox)

16 DisplayDie(die5PictureBox)

17 DisplayDie(die6PictureBox)

18 DisplayDie(die7PictureBox)

19 DisplayDie(die8PictureBox)

20 DisplayDie(die9PictureBox)

Outline

RollDie.vb

( 1 of 4 )

• An array version of the dice roll-counting applicationis shown in Fig. 8.7.

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

21 DisplayDie(die10PictureBox)

22 DisplayDie(die11PictureBox)

23 DisplayDie(die12PictureBox)

24

25 Dim total As Double = 0

26

27 ' total the die faces (used in percentage calculations)

28 For i = 1 To frequency.GetUpperBound(0)

29 total += frequency(i)

30 Next

31

32 displayTextBox.Text = "Face" & vbTab & "Frequency" & _

33 vbTab & "Percent" & vbNewLine

34

35 ' output frequency values

36 For i = 1 To frequency.GetUpperBound(0)

37 displayTextBox.Text &= i & vbTab & frequency(i) & _

38 vbTab & vbTab & String.Format("{0:P2}", _

39 frequency(i) / total) & "%" & vbNewLine

40 Next

41 End Sub ' rollButton_Click

Outline

Recording rolls in frequency.

Lines 36–40 replace lines 35–47 of Fig. 7.17

RollDie.vb

( 2 of 4 )

Fig. 8.7 | Using arrays to eliminate a Select Case statement. (Part 2 of 4.)

2009 Pearson Education, Inc. All rights reserved.

26

42

43 ' simulate roll, display proper image and increment frequency

44 Sub DisplayDie(ByVal diePictureBox As PictureBox)

45 Dim face As Integer = 1 + randomNumber.Next(6)

46

47 ' retrieve specific die image from resources

48 Dim pictureResource = My.Resources.ResourceManager.GetObject( _

49 String.Format("die{0}", face))

50

51 ' convert pictureResource to image type and load into PictureBox

52 diePictureBox.Image = CType(pictureResource, Image)

53

54 frequency(face) += 1 ' increment appropriate frequency counter

55 End Sub ' DisplayDie

56 End Class ' RollDie

Outline

Lines 62–75 of Fig. 7.17 are replaced by line 54.

Producing a random number from 1 to 6

RollDie.vb

( 3 of 4 )

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

1 ' Fig. 8.11: PassArray.vb

2 ' Passing arrays and individual array elements to methods.

3 Module PassArray

4 Sub Main()

5 Dim array1 As Integer() = New Integer() {1, 2, 3, 4, 5}

6

7 Console.WriteLine("EFFECTS OF PASSING AN ENTIRE ARRAY " & _

8 "BY REFERENCE:" & vbNewLine & vbNewLine & _

9 "The values of the original array are:")

10

11 ' display original elements of array1

12 For i = 0 To array1.GetUpperBound(0)

13 Console.Write(" " & array1(i))

14 Next

15

16 ModifyArray(array1) ' array is passed by reference

17 Console.WriteLine(vbNewLine & _

18 "The values of the modified array are:")

19

Outline

PassArray.vb

( 1 of 5 )

array1 is passed by reference to method ModifyArray

Fig. 8.11 | Passing arrays and individual array elementsto methods. (Part 1 of 5.)

2009 Pearson Education, Inc. All rights reserved.

36

20 ' display modified elements of array1

21 For i = 0 To array1.GetUpperBound(0)

22 Console.Write(" " & array1(i))

23 Next

24

25 Console.WriteLine(vbNewLine & vbNewLine & _

26 "EFFECTS OF PASSING AN ARRAY ELEMENT BY VALUE:" & vbNewLine & _

27 vbNewLine & "array1(3) before ModifyElementByVal: " & _

28 array1(3))

29

30 ModifyElementByVal(array1(3)) ' array element passed by value

31 Console.WriteLine("array1(3) after ModifyElementByVal: " & _

32 array1(3))

33 Console.WriteLine(vbNewLine & "EFFECTS OF PASSING AN " & _

34 "ARRAY ELEMENT BY REFERENCE: " & vbNewLine & vbNewLine & _

35 "array1(3) before ModifyElementByRef: " & array1(3))

36

37 ModifyElementByRef(array1(3)) ' array element passed by reference

38 Console.WriteLine("array1(3) after ModifyElementByRef: " & _

39 array1(3))

40 End Sub ' Main

Outline

array1(3) is passed by value to method ModifyElementByVal.

array1(3) is passed by reference to method ModifyElementByRef.

PassArray.vb

( 2 of 5 )

Fig. 8.11 | Passing arrays and individual array elementsto methods. (Part 2 of 5.)

2009 Pearson Education, Inc. All rights reserved.

37

41

42 ' method modifies array it receives (note ByVal)

43 Sub ModifyArray(ByVal arrayParameter As Integer())

44 For j = 0 To arrayParameter.GetUpperBound(0)

45 arrayParameter(j) *= 2 ' double the array element

46 Next

47 End Sub ' ModifyArray

48

49 ' method modifies integer passed to it

50 ' original is not modified (note ByVal)

51 Sub ModifyElementByVal(ByVal element As Integer)

52 Console.WriteLine("Value received in ModifyElementByVal: " & _

53 element)

54 element *= 2 ' double the array element

55 Console.WriteLine("Value calculated in ModifyElementByVal: " & _

56 element)

57 End Sub ' ModifyElementByVal

58

59 ' method modifies integer passed to it

Outline

ModifyArray doubles each element (passed by value).

ModifyElementByVal doubles an element passed by value.

PassArray.vb

( 3 of 5 )

Fig. 8.11 | Passing arrays and individual array elementsto methods. (Part 3 of 5.)

2009 Pearson Education, Inc. All rights reserved.

38

60 ' original is modified (note ByRef)

61 Sub ModifyElementByRef(ByRef element As Integer)

62 Console.WriteLine("Value received in ModifyElementByRef: " & _

63 element)

64 element *= 2 ' double the array element

65 Console.WriteLine("Value calculated in ModifyElementByRef: " & _

66 element)

67 End Sub ' ModifyElementByRef

68 End Module ' PassArray EFFECTS OF PASSING AN ENTIRE ARRAY BY REFERENCE: The values of the original array are: 1 2 3 4 5 The values of the modified array are: 2 4 6 8 10 (continued on next page...)

Outline

ModifyElementByRef doubles an element passed by reference.

PassArray.vb

( 4 of 5 )

Fig. 8.11 | Passing arrays and individual array elementsto methods. (Part 4 of 5.)

2009 Pearson Education, Inc. All rights reserved.

39

(continued from previous page…) EFFECTS OF PASSING AN ARRAY ELEMENT BY VALUE: array1(3) before ModifyElementByVal: 8 Value received in ModifyElementByVal: 8 Value calculated in ModifyElementByVal: 16 array1(3) after ModifyElementByVal: 8 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

Outline

PassArray.vb

(5 of 5 )

Common Programming Error 8.4When passing an array to a method, including an empty pair of parentheses after the array name is a syntax error.

Fig. 8.11 | Passing arrays and individual array elementsto methods. (Part 5 of 5.)

2009 Pearson Education, Inc. All rights reserved.

40

1 ' Fig. 8.12: ForEach.vb

2 ' Program uses For Each Next to find the minimum grade.

3 Module ForEach

4 Sub Main()

5 Dim gradeArray As Integer() = _

6 {77, 68, 86, 73, 98, 87, 89, 81, 70, 90, 86, 81}

7 Dim lowGrade As Integer = 100

8

9 ' use For Each Next to find the minimum grade

10 For Each grade In gradeArray

11 If grade < lowGrade Then

12 lowGrade = grade

13 End If

14 Next

15

16 Console.WriteLine("The minimum grade is: {0}", lowGrade)

17 End Sub ' Main

18 End Module ' ForEach The minimum grade is: 68

Outline

ForEach.vb

• The For Each…Next repetition statement iteratesthrough the values in a data structure, such as an array.

The For Each header specifies an element variable and the array.

Finding the minimum value in the array.

Fig. 8.12 | Using For Each...Next with an array.

2009 Pearson Education, Inc. All rights reserved.

41

1 ' Fig. 8.13: GradeBook.vb

2 ' GradeBook class uses an array to store test grades.

3 Public Class GradeBook

4 Private courseNameValue As String ' name of course

5 Private grades As Integer() ' array of student grades

6

7 ' two-argument constructor initializes courseNameValue and grades

8 Public Sub New(ByVal name As String, ByVal gradesArray As Integer())

9 CourseName = name ' initializes courseNameValue via property

10 grades = gradesArray ' store reference to gradesArray

11 End Sub ' New

12

13 ' property CourseName

14 Public Property CourseName() As String

15 Get

16 Return courseNameValue

17 End Get

18

Outline

GradeBook.vb

( 1 of 7 )

Array grades is declared as an instance variable.

Fig. 8.13 | GradeBook class using an array to store test grades. (Part 1 of 7.)

2009 Pearson Education, Inc. All rights reserved.

42

19 Set(ByVal name As String)

20 courseNameValue = name

21 End Set

22 End Property ' Course Name

23

24 ' display a welcome message to the GradeBook user

25 Public Sub DisplayMessage()

26 Console.WriteLine("Welcome to the grade book for " & vbNewLine & _

27 CourseName & vbNewLine)

28 End Sub ' DisplayMessage

29

30 ' perform various operations on the data

31 Public Sub ProcessGrades()

32 OutputGrades() ' output grades array

33

34 ' call method GetAverage to calculate the average grade

35 Console.WriteLine("Class average is {0:F2}", GetAverage())

36

Outline

ProcessGrades outputs a grade report.

GradeBook.vb

( 2 of 7 )

Fig. 8.13 | GradeBook class using an array to store test grades. (Part 2 of 7.)

2009 Pearson Education, Inc. All rights reserved.

43

37 ' call methods GetMinimum and GetMaximum

38 Console.WriteLine("Lowest grade is {0}", GetMinimum())

39 Console.WriteLine("Highest grade is {0}", GetMaximum())

40

41 ' call OutputBarChart to print grade distribution chart

42 OutputBarChart()

43 End Sub ' ProcessGrades

44

45 ' find minimum grade

46 Public Function GetMinimum() As Integer

47 Dim lowGrade As Integer = grades(0) ' assume grades(0) is smallest

48

49 ' loop through grades array

50 For Each grade In grades

51 ' if grade lower than lowGrade, assign it to lowGrade

52 If grade < lowGrade Then

53 lowGrade = grade ' new lowest grade

54 End If

55 Next

56

57 Return lowGrade ' return lowest grade

58 End Function ' GetMinimum

Outline

GetMinimum loops through the array and compares values to lowGrade.

ProcessGrades outputs a grade report.

GradeBook.vb

( 3 of 7 )

Fig. 8.13 | GradeBook class using an array to store test grades. (Part 3 of 7.)

2009 Pearson Education, Inc. All rights reserved.

44

59

60 ' find maximum grade

61 Public Function GetMaximum() As Integer

62 Dim highGrade As Integer = grades(0) ' assume grades(0) is largest

63

64 ' loop through grades array

65 For Each grade In grades

66 ' if grade greater than highGrade, assign it to highGrade

67 If grade > highGrade Then

68 highGrade = grade ' new highest grade

69 End If

70 Next

71

72 Return highGrade ' return highest grade

73 End Function ' GetMaximum

74

Outline

GradeBook.vb

( 4 of 7 )

Fig. 8.13 | GradeBook class using an array to store test grades. (Part 4 of 7.)

2009 Pearson Education, Inc. All rights reserved.

45

75 ' determine average grade for test

76 Public Function GetAverage() As Double

77 Dim total As Integer = 0 ' initialize total

78

79 ' sum grades

80 For Each grade In grades

81 total += grade

82 Next

83

84 ' return average of grades

85 Return (total / grades.Length)

86 End Function ' GetAverage

87

88 ' output bar chart displaying grade distribution

89 Public Sub OutputBarChart()

90 Console.WriteLine(vbNewLine & "Grade distribution:")

91

Outline

Using a For Each statement to total the values in grades.

GradeBook.vb

( 5 of 7 )

Fig. 8.13 | GradeBook class using an array to store test grades. (Part 5 of 7.)

2009 Pearson Education, Inc. All rights reserved.

46

92 ' stores frequency of grades in each range of 10 grades

93 Dim frequency As Integer() = New Integer(10) {}

94

95 ' for each grade, increment the appropriate frequency

96 For Each grade In grades

97 frequency(grade \ 10) += 1

98 Next

99

100 ' for each grade frequency, print bar in chart

101 For count = 0 To frequency.GetUpperBound(0)

102 ' output bar label ( "00-09: ", ..., "90-99: ", "100: " )

103 If count = 10 Then

104 Console.Write("{0, 5:D}: ", 100)

105 Else

106 Console.Write("{0, 2:D2}-{1, 2:D2}: ", _

107 count * 10, count * 10 + 9)

108 End If

109

Outline

Counting the frequency of each letter grade level.

The format string indicates the format D2 (two decimal digits).

GradeBook.vb

( 6 of 7 )

Fig. 8.13 | GradeBook class using an array to store test grades. (Part 6 of 7.)

2009 Pearson Education, Inc. All rights reserved.

47

110 ' print bar of asterisks

111 For stars As Integer = 0 To frequency(count) - 1

112 Console.Write("*")

113 Next stars

114

115 Console.WriteLine() ' start a new line of output

116 Next count

117 End Sub ' OutputBarChart

118

119 ' output the contents of the grades array

120 Public Sub OutputGrades()

121 Console.WriteLine("The grades are:" & vbNewLine)

122

123 ' output each student's grade

124 For student = 0 To grades.GetUpperBound(0)

125 Console.WriteLine("Student {0, 2:D}: {1, 3:D}", _

126 student + 1, grades(student))

127 Next

128

129 Console.WriteLine()

130 End Sub ' OutputGrades

131 End Class ' GradeBook

Outline

Printing the student number and grade for each student.

GradeBook.vb

( 7 of 7 )

Fig. 8.13 | GradeBook class using an array to store test grades. (Part 7 of 7.)

2009 Pearson Education, Inc. All rights reserved.

48

1 ' Fig. 8.14: GradeBookTest.vb

2 ' Create GradeBook object using any array of grades.

3 Module GradeBookTest

4 Sub Main()

5 ' array of student grades

6 Dim gradesArray As Integer() = _

7 {87, 68, 94, 100, 83, 78, 85, 91, 76, 87}

8 Dim gradeBooks As New GradeBook( _

9 "CS101 Introduction to Visual Basic Programming", gradesArray)

10 gradeBooks.DisplayMessage()

11 gradeBooks.ProcessGrades()

12 End Sub ' Main

13 End Module ' GradeBookTest

Outline

GradeBookTest.vb

( 1 of 3 )

Initializing gradesArrayto an array of grade values.

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.

49Welcome to the grade book for CS101 Introduction to Visual Basic Programming 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 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: *

Outline

GradeBookTest.vb

( 2 of 3 )

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 objectof 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

1 ' Fig. 8.15: SortTest.vb

2 ' Program creates random numbers and sorts them.

3 Public Class SortArray

4 Dim integerArray As Integer() = New Integer(9) {}

5

6 ' creates random generated numbers

7 Private Sub createButton_Click(ByVal sender As System.Object, _

8 ByVal e As System.EventArgs) Handles createButton.Click

9

10 Dim output As String = String.Empty

11 Dim randomNumber As Random = New Random()

12

13 sortedTextBox.Clear() ' clear sortedTextBox

14

Outline

SortTest.vb

( 1 of 3 )

• Sorting data is one of the most popular computingapplications.

• Method Sort of class Array sorts an array’s elementsinto ascending order (Fig. 8.15).

Fig. 8.15 | Sorting an array with method Array.Sort. (Part 1 of 3.)

2009 Pearson Education, Inc. All rights reserved.

52

15 ' create 10 random numbers and append to output

16 For i = 0 To integerArray.GetUpperBound(0)

17 integerArray(i) = randomNumber.Next(100)

18 output &= (integerArray(i) & vbNewLine)

19 Next

20

21 originalTextBox.Text = output ' display numbers

22 sortButton.Enabled = True ' enable Sort button

23 End Sub ' createButton_Click

24

25 ' sorts randomly generated numbers

26 Private Sub sortButton_Click(ByVal sender As System.Object, _

27 ByVal e As System.EventArgs) Handles sortButton.Click

28

29 Dim output As String = String.Empty

30

31 Array.Sort(integerArray) ' sort array integerArray

32

Outline

10 random values are assigned to integerArray and the contents are displayed.

array is sorted in ascending order.

SortTest.vb

( 2 of 3 )

Fig. 8.15 | Sorting an array with method Array.Sort. (Part 2 of 3.)

2009 Pearson Education, Inc. All rights reserved.

53

33 ' creates string with sorted numbers

34 For i = 0 To integerArray.GetUpperBound(0)

35 output &= (integerArray(i) & vbNewLine)

36 Next

37

38 sortedTextBox.Text = output ' display numbers

39 sortButton.Enabled = False ' disable Sort button

40 createButton.Focus() ' set focus to createButton

41 End Sub ' sortButton_Click

42 End Class ' SortTest

Outline

SortTest.vb

( 3 of 3 )

a) b)

Fig. 8.15 | Sorting an array with method Array.Sort. (Part 3 of 3.)

2009 Pearson Education, Inc. All rights reserved.

54

1 ' Fig. 8.16: LinearSearch.vb

2 ' Linear search of an array.

3 Module LinearSearch

4 ' iterates through array

5 Function Search(ByVal key As Integer, _

6 ByVal numbers As Integer()) As Integer

7

8 ' statement iterates linearly through array

9 For i = 0 To numbers.GetUpperBound(0)

10 If numbers(i) = key Then

11 Return i

12 End If

13 Next

14

15 Return -1 ' indicates the key was not found

16 End Function ' Search

17 End Module ' LinearSearch

Outline

LinearSearch.vb

Search compares each element of an array with a search key.

Fig. 8.16 | Method for performing a linear search.

2009 Pearson Education, Inc. All rights reserved.

55

1 ' Fig. 8.17: LinearSearchTest.vb

2 ' Linear search of an array.

3 Public Class LinearSearchTest

4 Dim array1 As Integer() = New Integer(19) {}

5

6 ' create random data

7 Private Sub createButton_Click(ByVal sender As System.Object, _

8 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 ' create string containing 20 random numbers

14 For i = 0 To array1.GetUpperBound(0)

15 array1(i) = randomNumber.Next(1000)

16 output &= (i & vbTab & array1(i) & vbNewLine)

17 Next

18

19 dataTextBox.Text = output ' display numbers

20 inputTextBox.Clear() ' clear search key text box

21 searchButton.Enabled = True ' enable search button

22 End Sub ' createButton_Click

Outline

LinearSearchTest.vb

( 1 of 3 )

Fig. 8.17 | Linear search of an array. (Part 1 of 3.)

2009 Pearson Education, Inc. All rights reserved.

56

23

24 ' search array for search key

25 Private Sub searchButton_Click(ByVal sender As System.Object, _

26 ByVal e As System.EventArgs) Handles searchButton.Click

27

28 ' if search key text box is empty, display

29 ' message and exit method

30 If String.IsNullOrEmpty(inputTextBox.Text) Then

31 MessageBox.Show("You must enter a search key.", "Error", _

32 MessageBoxButtons.OK, MessageBoxIcon.Error)

33 Exit Sub

34 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

Outline

Storing element as the result of a linear search.

LinearSearchTest.vb

( 2 of 3 )

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

1 ' Fig. 8.18: BinarySearchTest.vb

2 ' Binary search of an array using Array.BinarySearch.

3 Public Class BinarySearchTest

4 Dim array1 As Integer() = New Integer(19) {}

5

6 ' create random data

7 Private Sub createButton_Click(ByVal sender As System.Object, _

8 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 ' create random array elements

14 For i As Integer = 0 To array1.GetUpperBound(0)

15 array1(i) = randomNumber.Next(1000)

16 Next

17

18 Array.Sort(array1) ' sort array to enable binary searching

19

Outline

BinarySearchTest.vb

( 1 of 4 )

• If an array is sorted, the high-speed binarysearch technique can be used.

• Figure 8.18 uses method BinarySearch of classArray

Sort must be invoked before passing the array.

Fig. 8.18 | Binary search of an array. (Part 1 of 4.)

2009 Pearson Education, Inc. All rights reserved.

59

20 ' display sorted array elements

21 For i As Integer = 0 To array1.GetUpperBound(0)

22 output &= (i & vbTab & array1(i) & vbNewLine)

23 Next

24

25 dataTextBox.Text = output ' displays numbers

26 inputTextBox.Clear() ' clear search key text box

27 searchButton.Enabled = True ' enable search button

28 End Sub ' createButton_Click

29

30 ' search array for search key

31 Private Sub searchButton_Click(ByVal sender As System.Object, _

32 ByVal e As System.EventArgs) Handles searchButton.Click

33

34 ' if search key text box is empty, display

35 ' message and exit method

36 If String.IsNullOrEmpty(inputTextBox.Text) Then

37 MessageBox.Show("You must enter a search key.", "Error", _

38 MessageBoxButtons.OK, MessageBoxIcon.Error)

39 Exit Sub

40 End If

Outline

BinarySearchTest.vb

( 2 of 4 )

Fig. 8.18 | Binary search of an array. (Part 2 of 4.)

2009 Pearson Education, Inc. All rights reserved.

60

41

42 Dim searchKey As Integer = Convert.ToInt32(inputTextBox.Text)

43 Dim element As Integer = Array.BinarySearch(array1, searchKey)

44

45 If element >= 0 Then

46 resultLabel.Text = "Found Value in index " & element

47 Else

48 resultLabel.Text = "Value Not Found"

49 End If

50 End Sub ' searchButton_Click

51 End Class ' BinarySearchTest

Outline

The search key is converted to an integer.

Storing element as the result of a linear search.

Displaying the search result.

BinarySearchTest.vb

( 3 of 4 )

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

Fig. 8.19 | Two-dimensional array with three rows and four columns.

• Rectangular arrays represent tables of values in rows and columns.

• Figure 8.19 illustrates a 3-by-4 array.

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

1 ' Fig. 8.20: RectangularArray.vb

2 ' Initializing a rectangular array.

3 Module RectangularArray

4 Sub Main()

5 ' create rectangular array

6 Dim array1 As Integer(,)

7 array1 = New Integer(,) {{1, 2, 3}, {4, 5, 6}}

8

9 Console.WriteLine("Values in rectangular array1 by row are ")

10

Outline

RectangularArray.vb

( 1 of 2 )

• The program in Fig. 8.20 demonstrates the initializationof a rectangular array and the use of nestedFor Next loop.

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

11 ' output array1 elements

12 For i = 0 To array1.GetUpperBound(0)

13 For j = 0 To array1.GetUpperBound(1)

14 Console.Write(array1(i, j) & " ")

15 Next j

16

17 Console.WriteLine()

18 Next i

19 End Sub ' Main

20 End Module ' RectangularArray Values in rectangular array1 by row are 1 2 3 4 5 6

Outline

The inner For…Next statement traverses the columns within a row.

RectangularArray.vb

( 2 of 2 )

The outer For…Next statement traverses the rows

Fig. 8.20 | Initializing a rectangular array. (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

67

1 ' Fig. 8.21: GradeBook.vb

2 ' Grade book using a rectangular array to store grades.

3 Public Class GradeBook

4 Private courseNameValue As String ' name of course

5 Private grades As Integer(,) ' rectangular array of student grades

6

7 ' two-argument constructor initializes courseNameValue and Grades

8 Public Sub New(ByVal name As String, ByVal gradesArray As Integer(,))

9 CourseName = name ' initializes courseNameValue via property

10 grades = gradesArray ' store grades

11 End Sub ' New

12

13 ' property CourseName

14 Public Property CourseName() As String

15 Get

16 Return courseNameValue

17 End Get

18

Outline

GradeBook.vb

(1 of 8 )

• Figure 8.21 contains a version of class GradeBookthat uses a rectangular array.

• Method OutputBarChart uses nested loops toproduce a bar chart of student grades.

Initializing grades to a rectangular array

Setting grades to a rectangular array

Fig. 8.21 | GradeBook class using a rectangular array tostore grades. (Part 1 of 8.)

2009 Pearson Education, Inc. All rights reserved.

68

19 Set(ByVal name As String)

20 courseNameValue = name

21 End Set

22 End Property ' CourseName

23

24 ' display a welcome message to the GradeBook user

25 Public Sub DisplayMessage()

26 Console.WriteLine("Welcome to the grade book for " & vbNewLine & _

27 CourseName & vbNewLine)

28 End Sub ' DisplayMessage

29

30 ' perform various operations on the data

31 Public Sub ProcessGrades()

32 OutputGrades() ' output grades array

33

34 ' call methods GetMinimum and GetMaximum

35 Console.WriteLine("Lowest grade in the grade book is {0}", _

36 GetMinimum())

37 Console.WriteLine("Highest grade in the grade book is {0}", _

38 GetMaximum())

Outline

GradeBook.vb

( 2 of 8 )

Fig. 8.21 | GradeBook class using a rectangular array tostore grades. (Part 2 of 8.)

2009 Pearson Education, Inc. All rights reserved.

69

39

40 ' call OutputBarChart to print grade distribution chart

41 OutputBarChart()

42 End Sub ' ProcessGrades

43

44 ' find minimum grade

45 Public Function GetMinimum() As Integer

46 ' assume first element of grades array is smallest

47 Dim lowGrade As Integer = grades(0,0)

48

49 ' loop through grades array

50 For i = 0 To grades.GetUpperBound(0)

51 ' loop through columns of current row

52 For j = 0 To grades.GetUpperBound(1)

53 ' if grade lower than lowGrade, assign it to lowGrade

54 If grades(i,j) < lowGrade Then

55 lowGrade = grades(i,j) ' new lowest grade

56 End If

57 Next j

58 Next i

59

Outline

GetMinimum determines the lowest grade of any student.

GradeBook.vb

( 3 of 8 )

Fig. 8.21 | GradeBook class using a rectangular array tostore grades. (Part 3 of 8.)

2009 Pearson Education, Inc. All rights reserved.

70

60 Return lowGrade ' return lowest grade

61 End Function ' GetMinimum

62

63 ' find maximum grade

64 Public Function GetMaximum() As Integer

65 ' assume first element of grades array is largest

66 Dim highGrade As Integer = grades(0,0)

67

68 ' loop through grades array

69 For i = 0 To grades.GetUpperBound(0)

70 ' loop through columns of current row

71 For j = 0 To grades.GetUpperBound(1)

72 ' if grade greater than highGrade, assign it to highGrade

73 If grades(i,j) > highGrade Then

74 highGrade = grades(i,j) ' new highest grade

75 End If

76 Next j

77 Next i

78

79 Return highGrade ' return highest grade

80 End Function ' GetMaximum

Outline

GetMinimum determines the lowest grade of any student.

GetMaximum determines the highest grade of any student.

GradeBook.vb

( 4 of 8 )

Fig. 8.21 | GradeBook class using a rectangular array tostore grades. (Part 4 of 8.)

2009 Pearson Education, Inc. All rights reserved.

71

81

82 ' determine average grade for particular student’s grades

83 Public Function GetAverage(ByVal row As Integer) As Double

84 Dim total As Integer = 0 ' initialize total

85

86 ' sum grades for one student

87 For column = 0 To grades.GetUpperBound(1)

88 total += grades(row, column)

89 Next

90

91 ' return average of grades

92 Return (total / (grades.GetUpperBound(1) + 1))

93 End Function ' GetAverage

94

95 ' output bar chart displaying grade distribution

96 Public Sub OutputBarChart()

97 Console.WriteLine(vbNewLine & "Overall grade distribution:")

98

99 ' stores frequency of grades in each range of 10 grades

100 Dim frequency As Integer() = New Integer(10) {}

Outline

GetAverage determines a particular student’s average.

GradeBook.vb

( 5 of 8 )

Fig. 8.21 | GradeBook class using a rectangular array tostore grades. (Part 5 of 8.)

2009 Pearson Education, Inc. All rights reserved.

72

101

102 ' for each grade, increment the appropriate frequency

103 For i = 0 To grades.GetUpperBound(0)

104 For j = 0 To grades.GetUpperBound(1)

105 frequency(grades(i,j) \ 10) += 1

106 Next j

107 Next i

108

109 ' for each grade frequency, print bar in chart

110 For count = 0 To frequency.GetUpperBound(0)

111 ' output bar label ( "00-09: ", ..., "90-99: ", "100: " )

112 If count = 10 Then

113 Console.Write("{0, 5:D}: ", 100)

114 Else

115 Console.Write("{0, 2:D2}-{1, 2:D2}: ", _

116 count * 10, count * 10 + 9)

117 End If

118

Outline

Nested loops output a bar chart of student grades.

GradeBook.vb

( 6 of 8 )

Fig. 8.21 | GradeBook class using a rectangular array tostore grades. (Part 6 of 8.)

2009 Pearson Education, Inc. All rights reserved.

73

119 ' print bar of asterisks

120 For stars = 0 To frequency(count) - 1

121 Console.Write("*")

122 Next stars

123

124 Console.WriteLine() ' start a new line of output

125 Next count

126 End Sub ' OutputBarChart

127

128 ' output the contents of the grades array

129 Public Sub OutputGrades()

130 Console.WriteLine("The grades are:" & vbNewLine)

131 Console.Write(" ") ' align column heads

132

133 ' create a column heading for each of the tests

134 For test = 0 To grades.GetUpperBound(1)

135 Console.Write("Test {0:D} ", test + 1)

136 Next

137

Outline

OutputGrades outputs the array in a tabular format.

GradeBook.vb

( 7 of 8 )

Fig. 8.21 | GradeBook class using a rectangular array tostore grades. (Part 7 of 8.)

2009 Pearson Education, Inc. All rights reserved.

74

138 Console.WriteLine("Average") ' student average column heading

139

140 ' create rows/columns of text representing array grades

141 For student = 0 To grades.GetUpperBound(0)

142 Console.Write("Student {0, 2:D}", student + 1)

143

144 ' output student's grades

145 For counter = 0 To grades.GetUpperBound(1)

146 Console.Write("{0, 8:D}", grades(student, counter))

147 Next counter

148

149 ' call method GetAverage to calculate student's average grade;

150 ' pass row of grades as the argument to GetAverage

151 Dim average As Double = GetAverage(student)

152 Console.WriteLine("{0, 9:F2}", average)

153 Next student

154

155 Console.WriteLine()

156 End Sub ' OutputGrades

157 End Class ' GradeBook

Outline

OutputGrades outputs the array in a tabular format.

GradeBook.vb

( 8 of 8 )

Fig. 8.21 | GradeBook class using a rectangular array tostore grades. (Part 8 of 8.)

2009 Pearson Education, Inc. All rights reserved.

75

1 ' Fig. 8.22: GradeBookTest.vb

2 ' Create GradeBook object using a rectangular array of grades.

3 Module GradeBookTest

4 Sub Main()

5 ' array of student grades

6 Dim gradesArray As Integer(,)

7 gradesArray = New Integer(,) {{87, 96, 70}, {68, 87, 90}, _

8 {94, 37, 90}, {100, 81, 82}, {83, 65, 85}, {78, 87, 65}, _

9 {85, 75, 83}, {91, 59, 100}, {76, 72, 84}, {87, 93, 73}}

10

11 Dim gradeBooks As New GradeBook( _

12 "CS101 Introduction to Visual Basic Programming", gradesArray)

13 gradeBooks.DisplayMessage()

14 gradeBooks.ProcessGrades()

15 End Sub ' Main

16 End Module ' GradeBookTest Welcome to the grade book for CS101 Introduction to Visual Basic Programming

Outline

GradeBookTest.vb

( 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.

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: Test 1 Test 2 Test 3 Average Student 1 87 96 70 84.33 Student 2 68 87 90 81.67 Student 3 94 37 90 73.67 Student 4 100 81 82 87.67 Student 5 83 65 85 77.67 Student 6 78 87 65 76.67 Student 7 85 75 83 81.00 Student 8 91 59 100 83.33 Student 9 76 72 84 77.33 Student 10 87 93 73 84.33 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: **

Outline

GradeBookTest.vb

( 2 of 2 )

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

1 ' Fig. 8.23: ParamArrayTest.vb

2 ' Using ParamArray to create variable-length parameter lists.

3 Module ParamArrayTest

4 Sub Main()

5 AnyNumberOfArguments()

6 AnyNumberOfArguments(2, 3)

7 AnyNumberOfArguments(7, 8, 9, 10, 11, 12)

8 End Sub ' Main

9

Outline

ParamArrayTest.vb

( 1 of 3 )

• It’s possible to create methods that receive avariable number of arguments, using keywordParamArray.

• Figure 8.23 calls method AnyNumberOfArgumentsthree times, passing a different number of values each time.

A different number of arguments is used in each call.

Fig. 8.23 | Creating variable-length parameter lists. (Part 1 of 2.)

2009 Pearson Education, Inc. All rights reserved.

78

10 ' receives any number of arguments in array

11 Sub AnyNumberOfArguments(ByVal ParamArray array1 As Integer())

12 Dim total As Integer = 0

13

14 ' check number of arguments

15 If array1.Length = 0 Then

16 Console.WriteLine("Method AnyNumberOfArguments" & _

17 " received 0 arguments.")

18 Else

19 Console.Write("The total of ")

20

21 ' total array elements

22 For i = 0 To array1.GetUpperBound(0)

23 Console.Write(array1(i) & " ")

24 total += array1(i)

25 Next

26

27 Console.WriteLine("is {0}.", total)

28 End If

29 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.

Outline

Printing any arguments passed to the method.

ParamArrayTest.vb

( 2 of 3 )

Determining whether the number of arguments is zero.

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

1 ' Fig. 8.24: JaggedArray.vb

2 ' Initializing a jagged array.

3 Module JaggedArray

4 Sub Main()

5 ' create jagged array

6 Dim array1 As Integer()() = New Integer(2)() {} ' three rows

7 array1(0) = New Integer() {1, 2} ' row 0 is a single array

8 array1(1) = New Integer() {3} ' row 1 is a single array

9 array1(2) = New Integer() {4, 5, 6} ' row 2 is a single array

10

Outline

JaggedArray.vb

( 1 of 2 )

• Jagged arrays are maintained as arrays of arrays.

• The program in Fig. 8.24 demonstrates the use of ajagged array.

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

11 Console.WriteLine("Values in jagged array1 by row are ")

12

13 ' output array1 elements

14 For i = 0 To array1.GetUpperBound(0)

15 For j = 0 To array1(i).GetUpperBound(0)

16 Console.Write(array1(i)(j) & " ")

17 Next

18

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

Outline

The nested For statements traverse the jagged array.

JaggedArray.vb

( 2 of 2 )

Fig. 8.24 | Initializing a jagged array. (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

82

1 ' Fig. 8.25: ReDimTest.vb

2 ' Resize an array using the ReDim statement.

3 Module ReDimTest

4 Sub Main()

5 ' create and initialize a 5-element array

6 Dim array As Integer() = {1, 2, 3, 4, 5}

7 Dim arrayCopy As Integer() = array

8

9 ' display array length and the elements in array

10 Console.Write("The original array has {0} elements: ", _

11 array.Length)

12 DisplayArray(array)

13

14 ' change the size of the array without the Preserve keyword

15 ReDim array(6)

16

Outline

ReDimTest.vb

( 1 of 3 )

• The ReDim statement enables you to change thearray size (Fig. 8.25).

• To save the original data stored in an array, followReDim with Preserve.

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

17 ' display new array length and the elements in array

18 Console.Write("New array (without Preserve) has {0} elements: ", _

19 array.Length)

20 DisplayArray(array)

21

22 ' change the size of the array with the Preserve keyword

23 ReDim Preserve arrayCopy(6)

24 arrayCopy(6) = 7 ' assign 7 to array element 6

25

26 ' display new array length and the elements in array

27 Console.Write("New array (with Preserve) has {0} elements: ", _

28 arrayCopy.Length)

29 DisplayArray(arrayCopy)

30 End Sub ' Main

31

Outline

Preserve indicates the existing array elements are kept when the array is resized.

ReDimTest.vb

( 2 of 3 )

Fig. 8.25 | Using ReDim statements to change the array size. (Part 2 of 3.)

2009 Pearson Education, Inc. All rights reserved.

84

32 ' display array elements

33 Sub DisplayArray(ByVal array As Integer())

34 For Each number In array

35 Console.Write("{0} ", number)

36 Next

37

38 Console.WriteLine()

39 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

Outline

ReDimTest.vb

( 3 of 3 )

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.1Passing 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

1 ' Fig. 8.26: ArrayReferenceTest.vb

2 ' Testing the effects of passing array references using ByVal and ByRef.

3 Module ArrayReferenceTest

4 Sub Main()

5 ' declare array references

6 Dim firstArray As Integer()

7 Dim firstArrayCopy As Integer()

8

9 ' allocate firstArray and copy its reference

10 firstArray = New Integer() {1, 2, 3}

11 firstArrayCopy = firstArray ' reference preceding array

12

13 Console.WriteLine("Passing an array reference using ByVal.")

14 Console.Write("Contents of firstArray before calling FirstDouble: ")

15

16 ' print contents of firstArray

17 For i = 0 To firstArray.GetUpperBound(0)

18 Console.Write(firstArray(i) & " ")

19 Next

20

Outline

ArrayReferenceTest.vb

( 1 of 6 )

• The program in Fig. 8.26 demonstrates the difference between passing a reference ByVal and ByRef.

firstArrayCopy now refers to the same object as firstArray.

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

21 FirstDouble(firstArray) ' pass firstArray using ByVal

22 Console.Write(vbNewLine & "Contents of firstArray after " & _

23 "calling FirstDouble: ")

24

25 ' print contents of firstArray

26 For i = 0 To firstArray.GetUpperBound(0)

27 Console.Write(firstArray(i) & " ")

28 Next

29

30 ' was reference to firstArray changed by FirstDouble?

31 If firstArray Is firstArrayCopy Then

32 Console.WriteLine(vbNewLine & "The references are equal.")

33 Else

34 Console.WriteLine(vbNewLine & "The references are not equal.")

35 End If

36

37 ' declare array references

38 Dim secondArray As Integer()

39 Dim secondArrayCopy As Integer()

40

Outline

ArrayReferenceTest.vb

( 2 of 6 )

Fig. 8.26 | Passing an array reference with ByVal and ByRef. (Part 2 of 6.)

2009 Pearson Education, Inc. All rights reserved.

88

41 ' allocate secondArray and copy its reference

42 secondArray = New Integer() {1, 2, 3}

43 secondArrayCopy = secondArray

44

45 Console.WriteLine(vbNewLine & "Passing an array " & _

46 "reference using ByRef.")

47 Console.Write("Contents of secondArray before " & _

48 "calling SecondDouble: ")

49

50 ' print contents of secondArray before method call

51 For i = 0 To secondArray.GetUpperBound(0)

52 Console.Write(secondArray(i) & " ")

53 Next

54

55 SecondDouble(secondArray) ' pass secondArray using ByRef

56 Console.Write(vbNewLine & "Contents of secondArray " & _

57 "after calling SecondDouble: ")

58

Outline

ArrayReferenceTest.vb

( 3 of 6 )

Fig. 8.26 | Passing an array reference with ByVal and ByRef. (Part 3 of 6.)

2009 Pearson Education, Inc. All rights reserved.

89

59 ' print contents of secondArray after method call

60 For i = 0 To secondArray.GetUpperBound(0)

61 Console.Write(secondArray(i) & " ")

62 Next

63

64 ' was reference secondArray changed by SecondDouble

65 If secondArray Is secondArrayCopy Then

66 Console.WriteLine(vbNewLine & "The references are equal.")

67 Else

68 Console.WriteLine(vbNewLine & "The references are not equal.")

69 End If

70 End Sub ' Main

71

72 ' method modifies elements of array and assigns

73 ' new reference (note ByVal)

74 Sub FirstDouble(ByVal array As Integer())

75 ' double each element value in caller’s array

76 For i = 0 To array.GetUpperBound(0)

77 array(i) *= 2 ' double the ith element

78 Next

Outline

The For statement prints the contents of firstArray.

ArrayReferenceTest.vb

( 4 of 6 )

Fig. 8.26 | Passing an array reference with ByVal and ByRef. (Part 4 of 6.)

2009 Pearson Education, Inc. All rights reserved.

90

79

80 ' create a new array and assign its reference to the variable array

81 array = New Integer() {11, 12, 13}

82 End Sub ' FirstDouble

83

84 ' method modifies elements of array and assigns

85 ' new reference (note ByRef)

86 Sub SecondDouble(ByRef array As Integer())

87 ' double each element value in caller’s array

88 For i = 0 To array.GetUpperBound(0)

89 array(i) *= 2 ' double the ith element

90 Next

91

92 ' create a new array and assign its reference to the variable array

93 array = New Integer() {11, 12, 13} ' lose the 2, 4, 6 array

94 End Sub ' SecondDouble

95 End Module ' ArrayReferenceTest

Outline

FirstDouble multiplies the values of all the elements in the array by 2.

SecondDouble receives its array argument ByRef.

ArrayReferenceTest.vb

( 5 of 6 )

Fig. 8.26 | Passing an array reference with ByVal and ByRef. (Part 5 of 6.)

2009 Pearson Education, Inc. All rights reserved.

91

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.

Outline

ArrayReferenceTest.vb

( 6 of 6 )

Software Engineering Observation 8.2Using 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.

Fig. 8.26 | Passing an array reference with ByVal and ByRef. (Part 6 of 6.)