58
2002 Prentice Hall. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Allocating Arrays 7.4 Examples Using Arrays 7.4.1 Allocating an Array 7.4.2 Initializing the Values in an Array 7.4.3 Summing the Elements of an Array 7.4.4 Using Arrays to Analyze Survey Results 7.4.5 Using Histograms to Display Array Data Graphically 7.5 Passing Arrays to Procedures 7.6 Passing Arrays: ByVal vs. ByRef 7.7 Sorting Arrays 7.8 Searching Arrays: Linear Search and Binary Search 7.8.1 Searching an Array with Linear Search 7.8.2 Searching a Sorted Array with Binary Search 7.9 Multidimensional Rectangular and Jagged Arrays 7.10 Variable-Length Parameter Lists 7.11 For Each/Next Repetition Structure

2002 Prentice Hall. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1Introduction 7.2 Arrays 7.3 Declaring and Allocating Arrays 7.4 Examples Using

Embed Size (px)

Citation preview

2002 Prentice Hall. All rights reserved.

1

Chapter 7 - Arrays

Outline7.1 Introduction7.2   Arrays7.3   Declaring and Allocating Arrays7.4   Examples Using Arrays

7.4.1  Allocating an Array7.4.2  Initializing the Values in an Array7.4.3  Summing the Elements of an Array7.4.4  Using Arrays to Analyze Survey Results7.4.5  Using Histograms to Display Array Data

Graphically7.5   Passing Arrays to Procedures7.6   Passing Arrays: ByVal vs. ByRef7.7   Sorting Arrays7.8   Searching Arrays: Linear Search and Binary Search

7.8.1  Searching an Array with Linear Search7.8.2  Searching a Sorted Array with Binary Search

7.9   Multidimensional Rectangular and Jagged Arrays7.10   Variable-Length Parameter Lists7.11   For Each/Next Repetition Structure

2002 Prentice Hall. All rights reserved.

2

7.1 Introduction

• Arrays– Arrays are data structures consisting of data items of the

same type

– “Static” entities• They remain the same size once they are created

2002 Prentice Hall. All rights reserved.

3

7.2 Arrays

• Array– Group of contiguous memory locations that have the same

name and the me type

• Position number– Values that indicate specific locations within arrays– The first element in every array is the zeroth element

• Length property– Every array in Visual Basic “knows” its own length through

the Length property

• GetUpperBound method– Returns the index of the last element in the array– The value returned by this GetUpperBound is one less

than the value of the array’s Length property

2002 Prentice Hall. All rights reserved.

4

7.2 Arrays

Fig. 7.1 Array consisting of 12 elements.

-45numberArray(0)6numberArray(1)0numberArray(2)72numberArray(3)1543numberArray(4)-89numberArray(5)0numberArray(6)62numberArray(7)-3numberArray(8)1numberArray(9)

6453numberArray(10)78numberArray(11)

Name of array (note that all elements of this array have the

same name, numberArray)

Position number (index or subscript) of the element within array numberArray

2002 Prentice Hall. All rights reserved.

5

7.3 Declaring and Allocating Arrays

• Memory– The amount of memory required by an array depends on the length

of the array and the size of the data type of the elements in the array

• Keyword New– It is used to specify the size of the array and allocate memory for

the array

• Array bounds – Determine what indices can be used to access an element in the

array

• Initializer list– Specify the initial values of the elements in the array

• Keyword Nothing– Denotes an empty reference

2002 Prentice Hall. All rights reserved.

6

7.4 Examples Using Arrays

• Several examples that demonstrate– Declaration

– Allocation

– Initialization of arrays

2002 Prentice Hall.All rights reserved.

Outline7

CreateArray.vb

1 ' Fig. 7.2: CreateArray.vb2 ' Declaring and allocating an array.3 4 Imports System.Windows.Forms5 6 Module modCreateArray7 8 Sub Main()9 Dim output As String10 Dim i As Integer11 12 Dim array As Integer() ' declare array variable13 array = New Integer(9) {} ' allocate memory for array14 15 output &= "Subscript " & vbTab & "Value" & vbCrLf16 17 ' display values in array18 For i = 0 To array.GetUpperBound(0)19 output &= i & vbTab & array(i) & vbCrLf20 Next21 22 output &= vbCrLf & "The array contains " & _23 array.Length & " elements."24 25 MessageBox.Show(output, "Array of Integer Values", _26 MessageBoxButtons.OK, MessageBoxIcon.Information)27 End Sub ' Main28 29 End Module ' modCreateArray

A variable capable of storing a reference to an array of Integer elementsAllocate an array of 10 elements

using New and assigns it to arrayAppends to output the headings for the columns displayed by the programFor structure is used to append

the index number and value of each array element to output

The length property returns the number of elements in the array

2002 Prentice Hall.All rights reserved.

Outline8

CreateArray.vb

7.4 Examples Using Arrays

2002 Prentice Hall.All rights reserved.

Outline9

InitArray.vb

1 ' Fig. 7.3: InitArray.vb2 ' Initializing arrays.3 4 Imports System.Windows.Forms5 6 Module modInitArray7 8 Sub Main()9 Dim output As String10 Dim i As Integer11 12 Dim array1, array2 As Integer() ' declare two arrays13 14 ' initializer list specifies number of elements15 ' and value of each element16 array1 = New Integer() {32, 27, 64, 18, 95, _17 14, 90, 70, 60, 37}18 19 ' allocate array2 based on length of array120 array2 = New Integer(array1.GetUpperBound(0)) {}21 22 ' set values in array2 by a calculation23 For i = 0 To array2.GetUpperBound(0)24 array2(i) = 2 + 2 * i25 Next26 27 output &= "Subscript " & vbTab & "Array1" & vbTab & _28 "Array2" & vbCrLf29 30 ' display values for both arrays31 For i = 0 To array1.GetUpperBound(0)32 output &= i & vbTab & array1(i) & vbTab & array2(i) & _33 vbCrLf34 Next35

Uses the values in the arrays to build String output, which is displayed in a MessageBox

Initializes each element in array2 to the even integers

Allocates array2, whose size is determined by arry1.GetUpperBound(0), so that array1

and array2 have the same upper bound

Allocates the 10 elements of array1 with New and initialize the values in the array,

using an initializer list

One statement is used to declare the two arrays

2002 Prentice Hall.All rights reserved.

Outline10

InitArray.vb

36 MessageBox.Show(output, "Array of Integer Values", _37 MessageBoxButtons.OK, MessageBoxIcon.Information)38 End Sub ' Main39 40 End Module ' modInitArray

2002 Prentice Hall.All rights reserved.

Outline11

SumArray.vb

1 ' Fig. 7.4: SumArray.vb2 ' Computing sum of elements in array.3 4 Imports System.Windows.Forms5 6 Module modSumArray7 8 Sub Main()9 Dim array As Integer() = New Integer() _10 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}11 12 Dim total As Integer = 0, i As Integer = 013 14 ' sum array element values15 For i = 0 To array.GetUpperBound(0)16 total += array(i)17 Next18 19 MessageBox.Show("Total of array elements: " & total, _20 "Sum the elements of an Array", MessageBoxButtons.OK, _21 MessageBoxIcon.Information)22 End Sub ' Main23 24 End Module ' modSumArray

Declares, allocates and initializes the 10-element array, array

Performs the addition

2002 Prentice Hall.All rights reserved.

Outline12

StudentPoll.vb

1 ' Fig. 7.5: StudentPoll.vb2 ' Using arrays to display poll results.3 4 Imports System.Windows.Forms5 6 Module modStudentPoll7 8 Sub Main()9 Dim answer, rating As Integer10 Dim output As String11 12 ' student response array (typically input at run time)13 Dim responses As Integer()14 responses = New Integer() {1, 2, 6, 4, 8, 5, 9, 7, _15 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, _16 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10}17 18 ' response frequency array (indices 0 through 10)19 Dim frequency As Integer() = New Integer(10) {}20 21 ' count frequencies22 For answer = 0 To responses.GetUpperBound(0)23 frequency(responses(answer)) += 124 Next25 26 output &= "Rating " & vbTab & "Frequency " & vbCrLf27 28 For rating = 1 To frequency.GetUpperBound(0)29 output &= rating & vbTab & frequency(rating) & vbCrLf30 Next31

Array responses is a 40-element integer array containing the student’s

responses to the survey

Reads the responses from the array responses one at a time and increments one of the 10

counters in the frequency array

2002 Prentice Hall.All rights reserved.

Outline13

StudentPoll.vb

32 MessageBox.Show(output, "Student Poll Program", _33 MessageBoxButtons.OK, MessageBoxIcon.Information)34 End Sub ' Main35 36 End Module ' modStudentPoll

2002 Prentice Hall.All rights reserved.

Outline14

Histogram.vb

1 ' Fig. 7.6: Histogram.vb2 ' Using data to create histograms.3 4 Imports System.Windows.Forms5 6 Module modHistogram7 8 Sub Main()9 Dim output As String ' output string10 Dim i, j As Integer ' counters11 12 ' create data array13 Dim array1 As Integer() = New Integer() _14 {19, 3, 15, 7, 11, 9, 13, 5, 17, 1}15 16 output &= "Element " & vbTab & "Value " & vbTab & _17 "Histogram"18 19 For i = 0 To array1.GetUpperBound(0)20 output &= vbCrLf & i & vbTab & array1(i) & vbTab21 22 For j = 1 To array1(i)23 output &= "*" ' add one asterisk24 Next25 26 Next27 28 MessageBox.show(output, "Histogram Printing Program", _29 MessageBoxButtons.OK, MessageBoxIcon.Information)30 End Sub ' Main31 32 End Module ' modHistogram

Inner For structure counts from 1 to array(i), which is the value

in the ith index of array1

Nested For loops append the bars to the String that is displayed in the

MessageBox

2002 Prentice Hall.All rights reserved.

Outline15

Histogram.vb

2002 Prentice Hall.All rights reserved.

Outline16

RollDie.vb

1 ' Fig. 7.7: RollDie.vb2 ' Rolling 12 dice with frequency chart.3 4 ' Note: Directory.GetCurrentDirectory returns the directory of5 ' the folder where the current project is plus6 ' "bin/". This is where the images must be placed7 ' for the example to work properly.8 9 Imports System.IO10 Imports System.Windows.Forms11 12 Public Class FrmRollDie13 Inherits System.Windows.Forms.Form14 15 Dim randomNumber As Random = New Random()16 Dim frequency As Integer() = New Integer(6) {}17 18 ' labels19 Friend WithEvents lblDie1 As Label20 Friend WithEvents lblDie2 As Label21 Friend WithEvents lblDie3 As Label22 Friend WithEvents lblDie4 As Label23 Friend WithEvents lblDie5 As Label24 Friend WithEvents lblDie6 As Label25 Friend WithEvents lblDie7 As Label26 Friend WithEvents lblDie8 As Label27 Friend WithEvents lblDie9 As Label28 Friend WithEvents lblDie11 As Label29 Friend WithEvents lblDie10 As Label30 Friend WithEvents lblDie12 As Label31 32 ' text box33 Friend WithEvents txtDisplay As TextBox34

2002 Prentice Hall.All rights reserved.

Outline17

RollDie.vb

35 ' button36 Friend WithEvents cmdRoll As Button37 38 ' Visual Studio .NET generated code39 40 ' event handler for cmdRoll button41 Private Sub cmdRoll_Click(ByVal sender As System.Object, _42 ByVal e As System.EventArgs) Handles cmdRoll.Click43 44 ' pass labels to a method that 45 ' randomly assigns a face to each die46 DisplayDie(lblDie1)47 DisplayDie(lblDie2)48 DisplayDie(lblDie3)49 DisplayDie(lblDie4)50 DisplayDie(lblDie5)51 DisplayDie(lblDie6)52 DisplayDie(lblDie7)53 DisplayDie(lblDie8)54 DisplayDie(lblDie9)55 DisplayDie(lblDie10)56 DisplayDie(lblDie11)57 DisplayDie(lblDie12)58 59 Dim total As Double = 060 Dim i As Integer61 62 For i = 1 To frequency.GetUpperBound(0)63 total += frequency(i)64 Next65 66 txtDisplay.Text = "Face" & vbTab & vbTab & "Frequency" & _67 vbTab & vbTab & "Percent" & vbCrLf68

2002 Prentice Hall.All rights reserved.

Outline18

RollDie.vb

69 ' output frequency values70 For i = 1 To frequency.GetUpperBound(0)71 txtDisplay.Text &= i & vbTab & vbTab & frequency(i) & _72 vbTab & vbTab & vbTab & String.Format("{0:N}", _73 frequency(i) / total * 100) & "%" & vbCrLf74 Next75 76 End Sub ' cmdRoll_Click77 78 ' simulate roll, display proper 79 ' image and increment frequency80 Sub DisplayDie(ByVal lblDie As Label)81 Dim face As Integer = 1 + randomNumber.Next(6)82 83 lblDie.Image = _84 Image.FromFile(Directory.GetCurrentDirectory & _85 "\Images\die" & face & ".png")86 87 frequency(face) += 188 End Sub ' DisplayDie89 90 End Class ' FrmRollDie

Uses face’s value as the index for array frequency to determine which element should be incremented

Calculates random numbers from 1-6

We loop through array frequency to output the frequency values

2002 Prentice Hall.All rights reserved.

Outline19

RollDie.vb

2002 Prentice Hall. All rights reserved.

20

7.5 Passing Arrays to Procedures

• Passing the Array– Specify the name of the array without using parentheses

– Every array object “knows” its own upper bound• Do not need to pass the upper bound of the array as a separate

argument

– In Visual Basic, arrays always are passed by reference

• Receiving the array– The procedure’s parameter list must specify that an array

will be recieved

2002 Prentice Hall.All rights reserved.

Outline21

PassArray.vb

1 ' Fig. 7.8: PassArray.vb2 ' Passing arrays and individual array elements to procedures.3 4 Imports System.Windows.Forms5 6 Module modPassArray7 Dim output As String8 9 Sub Main()10 Dim array1 As Integer() = New Integer() {1, 2, 3, 4, 5}11 Dim i As Integer12 13 output = "EFFECTS OF PASSING ENTIRE ARRAY " & _14 "BY REFERENCE:" & vbCrLf & vbCrLf & _15 "The values of the original array are:" & vbCrLf16 17 ' display original elements of array118 For i = 0 To array1.GetUpperBound(0)19 output &= " " & array1(i)20 Next21 22 ModifyArray(array1) ' array is passed by reference23 24 output &= vbCrLf & _25 "The values of the modified array are:" & vbCrLf26 27 ' display modified elements of array128 For i = 0 To array1.GetUpperBound(0)29 output &= " " & array1(i)30 Next31

Appends the five elements of array1 to String output

Passes array1 to procedure ModifyArray

Appends the elements of array1 to output

2002 Prentice Hall.All rights reserved.

Outline22

PassArray.vb

32 output &= vbCrLf & vbCrLf & _33 "EFFECTS OF PASSING ARRAY ELEMENT " & _34 "BY VALUE:" & vbCrLf & vbCrLf & "array1(3) " & _35 "before ModifyElementByVal: " & array1(3)36 37 ' array element passed by value38 ModifyElementByVal(array1(3))39 40 output &= vbCrLf & "array1(3) after " & _41 "ModifyElementByVal: " & array1(3)42 43 output &= vbCrLf & vbCrLf & "EFFECTS OF PASSING " & _44 "ARRAY ELEMENT BY REFERENCE: " & vbCrLf & vbCrLf & _45 "array1(3) before ModifyElementByRef: " & array1(3)46 47 ' array element passed by reference48 ModifyElementByRef(array1(3))49 50 output &= vbCrLf & "array1(3) after " & _51 "ModifyElementByRef: " & array1(3)52 53 MessageBox.Show(output, "Passing Arrays", _54 MessageBoxButtons.OK, MessageBoxIcon.Information)55 End Sub ' Main56 57 ' procedure modifies array it receives (note ByVal)58 Sub ModifyArray(ByVal arrayParameter As Integer())59 Dim j As Integer60 61 For j = 0 To arrayParameter.GetUpperBound(0)62 arrayParameter(j) *= 263 Next64 65 End Sub ' ModifyArray66

Multiplies the elements of arrayParameter by 2

2002 Prentice Hall.All rights reserved.

Outline23

PassArray.vb

67 ' procedure modifies integer passed to it68 ' original is not be modified (note ByVal)69 Sub ModifyElementByVal(ByVal element As Integer)70 71 output &= vbCrLf & "Value received in " & _72 "ModifyElementByVal: " & element73 element *= 274 output &= vbCrLf & "Value calculated in " & _75 "ModifyElementByVal: " & element76 End Sub ' ModifyElementByVal77 78 ' procedure modifies integer passed to it79 ' original is be modified (note ByRef)80 Sub ModifyElementByRef(ByRef element As Integer)81 82 output &= vbCrLf & "Value received in " & _83 "ModifyElementByRef: " & element84 element *= 285 output &= vbCrLf & "Value calculated in " & _86 "ModifyElementByRef: " & element87 End Sub ' ModifyElementByRef88 89 End Module ' modPassArray

2002 Prentice Hall.All rights reserved.

Outline24

PassArray.vb

2002 Prentice Hall. All rights reserved.

25

7.6 Passing Arrays: ByVal vs. ByRef

• Visual Basic.NET– A variable that “stores” an object, such as an array, does not

actually store the object itself– The variable stores a reference to the object

• Location in memory where the object is already stored

• ByVal– Causes the value of the argument to be copied to a local

variable in the procedure– Changes to the local variable are reflected in the local copy

of that variable, not in the original variable in the calling program

– But if the argument is of a reference type, like an array, passing it ByVal actually passes it by reference, so changes to the object affect the original objects in the callers

2002 Prentice Hall. All rights reserved.

26

7.6 Passing Arrays: ByVal vs. ByRef

• ByRef– When an array is passed with ByRef the called procedure

gains control over the passed reference itself• This allows the called procedure to replace the original

reference in the object with another object or even Nothing

2002 Prentice Hall.All rights reserved.

Outline27

ArrayReferenceTest.vb

1 ' Fig. 7.9: ArrayReferenceTest.vb2 ' Testing the effects of passing array references using 3 ' ByVal and ByRef.4 5 Module modArrayReferenceTest6 7 Sub Main()8 Dim i As Integer9 10 ' declare array references11 Dim firstArray As Integer()12 Dim firstArrayCopy As Integer()13 14 ' allocate firstArray and copy its reference15 firstArray = New Integer() {1, 2, 3}16 firstArrayCopy = firstArray17 18 Console.WriteLine("Test passing array reference " & _19 "using ByVal.")20 Console.Write("Contents of firstArray before " & _21 "calling FirstDouble: ")22 23 ' print contents of firstArray24 For i = 0 To firstArray.GetUpperBound(0)25 Console.Write(firstArray(i) & " ")26 Next27 28 ' pass firstArray using ByVal29 FirstDouble(firstArray)30 31 Console.Write(vbCrLf & "Contents of firstArray after " & _32 "calling FirstDouble: ")33

firstArray is passed to FirstDouble

Prints contents first to verify that FirstDouble indeed changes the array’s contents

Copies reference firstArray to variable firstArrayCopy, now

they reference the same object

2002 Prentice Hall.All rights reserved.

Outline28

ArrayReferenceTest.vb

34 ' print contents of firstArray35 For i = 0 To firstArray.GetUpperBound(0)36 Console.Write(firstArray(i) & " ")37 Next38 39 ' test whether reference was changed by FirstDouble40 If firstArray Is firstArrayCopy Then41 Console.WriteLine(vbCrLf & "The references are " & _42 "equal.")43 Else44 Console.WriteLine(vbCrLf & "The references are " & _45 "not equal.")46 End If47 48 ' declare array references49 Dim secondArray As Integer()50 Dim secondArrayCopy As Integer()51 52 ' allocate secondArray and copy its reference53 secondArray = New Integer() {1, 2, 3}54 secondArrayCopy = secondArray55 56 Console.WriteLine(vbCrLf & "Test passing array " & _57 "reference using ByRef.")58 Console.Write("Contents of secondArray before " & _59 "calling SecondDouble: ")60 61 ' print contents of secondArray before procedure call62 For i = 0 To secondArray.GetUpperBound(0)63 Console.Write(secondArray(i) & " ")64 Next65 66 ' pass secondArray using ByRef67 SecondDouble(secondArray)68

Compares references firstArray and firstArrayCopy

2002 Prentice Hall.All rights reserved.

Outline29

ArrayReferenceTest.vb

69 Console.Write(vbCrLf & "Contents of secondArray " & _70 "after calling SecondDouble: ")71 72 ' print contents of secondArray after procedure call73 For i = 0 To secondArray.GetUpperBound(0)74 Console.Write(secondArray(i) & " ")75 Next76 77 ' test whether the reference was changed by SecondDouble78 If secondArray Is secondArrayCopy Then79 Console.WriteLine(vbCrLf & "The references are " & _80 "equal.")81 Else82 Console.WriteLine(vbCrLf & "The references are " & _83 "not equal.")84 End If85 86 End Sub ' Main87 88 ' procedure modifies elements of array and assigns 89 ' new reference (note ByVal)90 Sub FirstDouble(ByVal array As Integer())91 Dim i As Integer92 93 ' double each element value94 For i = 0 To array.GetUpperBound(0)95 array(i) *= 296 Next97 98 ' create new reference and assign it to array99 array = New Integer() {11, 12, 13}100 End Sub ' FirstDouble101

Allocates a new array, and attempts to assign it’s reference to parameter array, attempting to overwrite reference firstArray in memory, but

will fail because the reference was passed ByVal

Multiplies all the elements of the array by 2

Reference is passed ByVal

2002 Prentice Hall.All rights reserved.

Outline30

ArrayReferenceTest.vb

102 ' procedure modifies elements of array and assigns103 ' new reference (note ByRef)104 Sub SecondDouble(ByRef array As Integer())105 Dim i As Integer106 107 ' double contents of array108 For i = 0 To array.GetUpperBound(0)109 array(i) *= 2110 Next111 112 ' create new reference and assign it to array113 array = New Integer() {11, 12, 13}114 End Sub ' SecondDouble115 116 End Module ' modPassArray

Test passing array reference using ByVal.Contents of firstArray before calling FirstDouble: 1 2 3Contents of firstArray after calling FirstDouble: 2 4 6The references are equal. Test passing array reference using ByRef.Contents of secondArray before calling SecondDouble: 1 2 3Contents of secondArray after calling SecondDouble: 11 12 13The references are not equal.

Because the reference was passed with ByRef, the called procedure has the ability to modify what the reference

actually points to

Reference is passed ByRef

2002 Prentice Hall. All rights reserved.

31

7.7 Sorting Arrays

• Sorting– Sorting data is one of the most popular computing

applications

– Sometimes, the simplest algorithms perform poorly

• Bubble Sort (a.k.a. sinking sort)– Smaller values “bubble” their way to the top of the array,

(i.e. toward the first element)

– Larger values “sink” to the bottom of the array, (i.e. toward the end)

– In general only n-1 passes are needed to sort an n-element array

– The bubble sort is easy to program, but runs slowly• Becomes apparent when sorting large arrays

2002 Prentice Hall.All rights reserved.

Outline32

BubbleSort.vb

1 ' Fig. 7.10: BubbleSort.vb2 ' Procedures for sorting an integer array.3 4 Module modBubbleSort5 6 ' sort array using bubble sort algorithm7 Sub BubbleSort(ByVal sortArray As Integer())8 Dim pass, i As Integer9 10 For pass = 1 To sortArray.GetUpperBound(0)11 12 For i = 0 To sortArray.GetUpperBound(0) - 113 14 If sortArray(i) > sortArray(i + 1) Then15 Swap(sortArray, i)16 End If17 18 Next19 20 Next21 22 End Sub ' BubbleSort23 24 ' swap two array elements25 Sub Swap(ByVal swapArray As Integer(), _26 ByVal first As Integer)27 28 Dim hold As Integer29 30 hold = swapArray(first)31 swapArray(first) = swapArray(first + 1)32 swapArray(first + 1) = hold33 End Sub ' Swap34 35 End Module ' modBubbleSort

Sorts the elements of it’s parameter sortArray

The nested For/Next structure performs the sortThis inner loop controls the comparisons and swapping, if necessary, of the elements

during each pass

Gets called by BubbleSort to transpose two of the array elements

2002 Prentice Hall.All rights reserved.

Outline33

BubbleSortTest.vb

1 ' Fig. 7.11: BubbleSortTest.vb2 ' Program creates random numbers and sorts them.3 4 Imports System.Windows.Forms5 6 Public Class FrmBubbleSort7 Inherits System.Windows.Forms.Form8 9 ' buttons10 Friend WithEvents cmdCreate As Button11 Friend WithEvents cmdSort As Button12 13 ' labels14 Friend WithEvents lblOriginal As Label15 Friend WithEvents lblSorted As Label16 17 ' textboxes18 Friend WithEvents txtOriginal As TextBox19 Friend WithEvents txtSorted As TextBox20 21 ' Visual Studio .NET generated code22 23 Dim array As Integer() = New Integer(9) {}24 25 ' creates random generated numbers26 Private Sub cmdCreate_Click(ByVal sender As System.Object, _27 ByVal e As System.EventArgs) Handles cmdCreate.Click28 29 Dim output As String30 Dim randomNumber As Random = New Random()31 Dim i As Integer32 33 txtSorted.Text = ""34

2002 Prentice Hall.All rights reserved.

Outline34

BubbleSortTest.vb

35 ' create 10 random numbers and append to output36 For i = 0 To array.GetUpperBound(0)37 array(i) = randomNumber.Next(100)38 output &= array(i) & vbCrLf39 Next40 41 txtOriginal.Text = output ' display numbers 42 cmdSort.Enabled = True ' enables cmdSort button 43 End Sub ' cmdCreate_Click44 45 ' sorts randomly generated numbers46 Private Sub cmdSort_Click(ByVal sender As System.Object, _47 ByVal e As System.EventArgs) Handles cmdSort.Click48 49 Dim output As String50 Dim i As Integer51 52 ' sort array53 modBubbleSort.BubbleSort(array)54 55 ' creates string with sorted numbers56 For i = 0 To array.GetUpperBound(0)57 output &= array(i) & vbCrLf58 Next59 60 txtSorted.Text = output ' display numbers61 cmdSort.Enabled = False62 End Sub ' cmdSort_Click63 64 End Class ' FrmBubbleSort

2002 Prentice Hall.All rights reserved.

Outline35

BubbleSortTest.vb

2002 Prentice Hall. All rights reserved.

36

7.8 Searching Arrays: Linear Search and Binary Search

• Searching– The process of locating a particular element value in an array

• Linear Search– Simple searching technique– Works well for small or unsorted arrays– On average half the elements of the array will be compared

• Binary Search– If array is sorted, binary search is more efficient, but also a

more complex technique– After each comparison, the binary search algorithm

eliminates half of the elements in the array– The maximum number of comparisons in a binary search is

the exponent of the first power of 2 that is greater than the number of elements being searched

2002 Prentice Hall.All rights reserved.

Outline37

LinearSearch.vb

1 ' Fig. 7.12: LinearSearch.vb2 ' Linear search of an array.3 4 Module modLinearSearch5 6 ' iterates through array 7 Function LinearSearch(ByVal key As Integer, _8 ByVal numbers As Integer()) As Integer9 10 Dim n As Integer11 12 ' structure iterates linearly through array13 For n = 0 To numbers.GetUpperBound(0)14 15 If numbers(n) = key Then16 17 Return n18 End If19 20 Next21 22 Return -123 End Function ' LinearSearch24 25 End Module ' modLinearSearch

Compares each element of the array with a search key

If the search key is not found, the procedure returns –1, a non-valid index number

2002 Prentice Hall.All rights reserved.

Outline38

LinearSearchTest.vb

1 ' Fig. 7.13: LinearSearchTest.vb2 ' Linear search of an array.3 4 Imports System.Windows.Forms5 6 Public Class FrmLinearSearchTest7 Inherits System.Windows.Forms.Form8 9 ' buttons10 Friend WithEvents cmdSearch As Button11 Friend WithEvents cmdCreate As Button12 13 ' text boxes14 Friend WithEvents txtInput As TextBox15 Friend WithEvents txtData As TextBox16 17 ' labels18 Friend WithEvents lblEnter As Label19 Friend WithEvents lblResult As Label20 21 ' Visual Studio .NET generated code22 23 Dim array1 As Integer() = New Integer(19) {}24 25 ' creates random data 26 Private Sub cmdCreate_Click(ByVal sender As System.Object, _27 ByVal e As System.EventArgs) Handles cmdCreate.Click28 29 Dim output As String30 Dim randomNumber As Random = New Random()31 Dim i As Integer32 33 output = "Index" & vbTab & "Value" & vbCrLf34

2002 Prentice Hall.All rights reserved.

Outline39

LinearSearchTest.vb

35 ' creates string containing 11 random numbers36 For i = 0 To array1.GetUpperBound(0)37 array1(i) = randomNumber.Next(1000)38 output &= i & vbTab & array1(i) & vbCrLf39 Next40 41 txtData.Text = output ' displays numbers 42 txtInput.Text = "" ' clear search key text box43 cmdSearch.Enabled = True ' enable search button44 End Sub ' cmdCreate_Click45 46 ' searches key of element 47 Private Sub cmdSearch_Click(ByVal sender As System.Object, _48 ByVal e As System.EventArgs) Handles cmdSearch.Click49 50 ' if search key text box is empty, display 51 ' message and exit procedure52 If txtInput.Text = "" Then53 MessageBox.Show("You must enter a search key.")54 Exit Sub55 End If56 57 Dim searchKey As Integer = Convert.ToInt32(txtInput.Text)58 Dim element As Integer = LinearSearch(searchKey, array1)59 60 If element <> -1 Then61 lblResult.Text = "Found Value in index " & element62 Else63 lblResult.Text = "Value Not Found"64 End If65 66 End Sub ' cmdSearch_Click67 68 End Class ' FrmLinearSearch

2002 Prentice Hall.All rights reserved.

Outline40

LinearSearchTest.vb

2002 Prentice Hall.All rights reserved.

Outline41

BinarySearchTest.vb

1 ' Fig. 7.14: BinarySearchTest.vb2 ' Demonstrating binary search of an array.3 4 Imports System.Windows.Forms5 6 Public Class FrmBinarySearch7 Inherits System.Windows.Forms.Form8 9 ' labels10 Friend WithEvents lblEnterKey As Label11 Friend WithEvents lblResult As Label12 Friend WithEvents lblResultOutput As Label13 Friend WithEvents lblDisplay As Label14 Friend WithEvents lblIndex As Label15 Friend WithEvents lblIndexes As Label16 17 ' button18 Friend WithEvents cmdFindKey As Button19 20 ' text box21 Friend WithEvents txtInput As TextBox22 23 ' Visual Studio .NET generated code24 25 Dim array1 As Integer() = New Integer(14) {}26 27 ' FrmBinarySearch initializes array1 to ascending values28 ' 0, 2, 4, 6, ..., 28 when first loaded29 Private Sub FrmBinarySearch_Load(ByVal sender As System.Object, _30 ByVal e As System.EventArgs) Handles MyBase.Load31 32 Dim i As Integer33

2002 Prentice Hall.All rights reserved.

Outline42

BinarySearchTest.vb

34 For i = 0 To array1.GetUpperBound(0)35 array1(i) = 2 * i36 Next37 38 End Sub ' FrmBinarySearch_Load39 40 ' event handler for cmdFindKey button41 Private Sub cmdFindKey_Click(ByVal sender As System.Object, _42 ByVal e As System.EventArgs) Handles cmdFindKey.Click43 44 Dim searchKey As Integer = Convert.ToInt32(txtInput.Text)45 46 lblDisplay.Text = ""47 48 ' perform binary search49 Dim element As Integer = BinarySearch(array1, searchKey)50 51 If element <> -1 Then52 lblResultOutput.Text = "Found value in element " & element53 Else54 lblResultOutput.Text = "Value not found"55 End If56 57 End Sub ' cmdFindKey_Click58 59 ' performs binary search60 Function BinarySearch(ByVal array As Integer(), _61 ByVal key As Integer) As Integer62 63 Dim low As Integer = 0 ' low index64 Dim high As Integer = array.GetUpperBound(0) ' high index 65 Dim middle As Integer ' middle index66

Receives two arguments, the array to search, and the search key

2002 Prentice Hall.All rights reserved.

Outline43

BinarySearchTest.vb

67 While low <= high68 middle = (low + high) \ 269 70 ' the following line displays part71 ' of the array being manipulated during72 ' each iteration of loop73 BuildOutput(low, middle, high)74 75 If key = array(middle) Then ' match76 Return middle77 ElseIf key < array(middle) Then ' search low end78 high = middle - 1 ' of array79 Else80 low = middle + 181 End If82 83 End While84 85 Return -1 ' search key not found86 End Function ' BinarySearch87 88 Sub BuildOutput(ByVal low As Integer, _89 ByVal middle As Integer, ByVal high As Integer)90 91 Dim i As Integer92

Calculates the middle element of the arrayIf middle matches key, then middle is returned

If key does not match middle, then the low or high index is adjusted so that a smaller subarray can be searched

2002 Prentice Hall.All rights reserved.

Outline44

BinarySearchTest.vb

93 For i = 0 To array1.GetUpperBound(0)94 95 If i < low OrElse i > high Then96 lblDisplay.Text &= " "97 ElseIf i = middle Then ' mark middle element in output98 lblDisplay.Text &= String.Format("{0:D2}", _99 array1(i)) & "* "100 Else101 lblDisplay.Text &= String.Format("{0:D2}", _102 array1(i)) & " "103 End If104 105 Next i106 107 lblDisplay.Text &= vbCrLf108 End Sub ' BuildOutput109 110 End Class ' FrmBinarySearch

2002 Prentice Hall.All rights reserved.

Outline45

BinarySearchTest.vb

2002 Prentice Hall. All rights reserved.

46

7.9 Multidimensional Rectangular and Jagged Arrays

• Multidimensional arrays (multiple-subscripted)– Require two or more indices to identify particular elements

• Rectangular arrays– Two indices, first identifies the element’s row, the second

the elements column

– A rectangular two-dimensional array with m rows and n columns is called an m-by-n array

• Jagged arrays– Jagged arrays are maintained as arrays of arrays

– Rows in jagged arrays can be of different lengths

2002 Prentice Hall. All rights reserved.

47

7.9 Multidimensional Rectangular and Jagged Arrays

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

a(0, 2) a(0, 3)a(0, 1)a(0, 0)

a(1, 2) a(1, 3)a(1, 1)a(1, 0)

a(2, 2) a(2, 3)a(2, 1)a(2, 0)

Column 0 Column 1 Column 2 Column 3

Row 0

Row 1

Row 2

Column index

Row index (or subscript)

Array name

2002 Prentice Hall.All rights reserved.

Outline48

MultidimensionalArrays.vb

1 ' Fig. 7.16: MultidimensionalArrays.vb2 ' Initializing multi-dimensional arrays.3 4 Imports System.Windows.Forms5 6 Module modMultidimensionalArrays7 8 Sub Main()9 Dim output As String10 Dim i, j As Integer11 12 ' create rectangular two-dimensional array13 Dim array1 As Integer(,)14 array1 = New Integer(,) {{1, 2, 3}, {4, 5, 6}}15 16 ' create jagged two-dimensional array17 Dim array2 As Integer()() = New Integer(2)() {}18 19 array2(0) = New Integer() {1, 2}20 array2(1) = New Integer() {3}21 array2(2) = New Integer() {4, 5, 6}22 23 output = "Values in array1 by row are " & vbCrLf24 25 For i = 0 To array1.GetUpperBound(0)26 27 For j = 0 To array1.GetUpperBound(1)28 output &= array1(i, j) & " "29 Next30 31 output &= vbCrLf32 Next33

Traverses the array in two dimensions

The declaration and allocation of array2 creates a jagged array of 3 arrays

Allocates array1 with six initializers in two sublists

2002 Prentice Hall.All rights reserved.

Outline49

MultidimensionalArrays.vb

34 output &= vbCrLf & "Values in array2 by row are " & _35 vbCrLf36 37 For i = 0 To array2.GetUpperBound(0)38 39 For j = 0 To array2(i).GetUpperBound(0)40 output &= array2(i)(j) & " "41 Next42 43 output &= vbCrLf44 Next45 46 MessageBox.Show(output, _47 "Initializing Multi-Dimensional Arrays", _48 MessageBoxButtons.OK, MessageBoxIcon.Information)49 End Sub ' Main50 51 End Module ' modMultidimensionalArrays

In a jagged two-dimensional array, the second dimension is actually the first dimension of a separate array

2002 Prentice Hall.All rights reserved.

Outline50

JaggedArray.vb

1 ' Fig 7.17: JaggedArray.vb2 ' Jagged two-dimensional array example.3 4 Imports System.Windows.Forms5 6 Module modJaggedArray7 Dim lastStudent, lastExam As Integer8 Dim output As String9 10 Sub Main()11 Dim i As Integer12 13 ' jagged array with 3 rows of exam scores14 Dim gradeArray As Integer()() = New Integer(2)() {}15 16 ' allocate each row with 4 student grades17 gradeArray(0) = New Integer() {77, 68, 86, 73}18 gradeArray(1) = New Integer() {98, 87, 89, 81}19 gradeArray(2) = New Integer() {70, 90, 86, 81}20 21 ' upper bounds for array manipulations22 lastStudent = gradeArray.GetUpperBound(0)23 lastExam = gradeArray(0).GetUpperBound(0)24 25 output = "Students \ Exams" & vbCrLf26 27 ' build output string28 BuildString(gradeArray)29 output &= vbCrLf & vbCrLf & "Lowest grade: " & _30 Minimum(gradeArray) & vbCrLf & "Highest grade: " & _31 Maximum(gradeArray) & vbCrLf32

2002 Prentice Hall.All rights reserved.

Outline51

JaggedArray.vb

33 ' calculate each student's average34 For i = 0 To lastStudent35 output &= vbCrLf & "Average for student " & _36 i & " is " & Average(gradeArray(i))37 Next38 39 MessageBox.Show(output, "Jagged two-dimensional array", _40 MessageBoxButtons.OK, MessageBoxIcon.Information)41 End Sub ' Main42 43 ' find minimum grade44 Function Minimum(ByVal grades As Integer()()) _45 As Integer46 47 Dim lowGrade As Integer = 10048 Dim i, j As Integer49 50 For i = 0 To lastStudent51 52 For j = 0 To lastExam53 54 If grades(i)(j) < lowGrade Then55 lowGrade = grades(i)(j)56 End If57 58 Next59 60 Next61 62 Return lowGrade63 End Function ' Minimum64

Determines the lowest grade of any student for the semester

2002 Prentice Hall.All rights reserved.

Outline52

JaggedArray.vb

65 ' find the maximum grade66 Function Maximum(ByVal grades As Integer()()) _67 As Integer68 69 Dim highGrade As Integer = 070 Dim i, j As Integer71 72 For i = 0 To lastStudent73 74 For j = 0 To lastExam75 76 If grades(i)(j) > highGrade Then77 highGrade = grades(i)(j)78 End If79 80 Next81 82 Next83 84 Return highGrade85 End Function ' Maximum86 87 ' determine the average grade for student88 ' (or set of grades)89 Function Average(ByVal setOfGrades As Integer()) _90 As Double91 92 Dim i As Integer, total As Integer = 093 94 ' find sum of student's grades95 For i = 0 To lastExam96 total += setOfGrades(i)97 Next98 99 Return total / setOfGrades.Length100 End Function ' Average

Determines the highest grade of any student for the semester

Determines a particular student’s semester average

2002 Prentice Hall.All rights reserved.

Outline53

JaggedArray.vb

101 102 ' creates String displaying array103 Sub BuildString(ByVal grades As Integer()())104 Dim i, j As Integer105 106 ' align column heads107 output &= " "108 109 For i = 0 To lastExam110 output &= "(" & i & ") "111 Next112 113 For i = 0 To lastStudent114 output &= vbCrLf & " (" & i & ") "115 116 For j = 0 To lastExam117 output &= grades(i)(j) & " "118 Next119 120 Next121 122 End Sub ' BuildString123 124 End Module ' modJaggedArray

Appends the two dimensional array to string output in tabular format

2002 Prentice Hall. All rights reserved.

54

7.10 Variable-Length Parameter Lists

• Keyword ParamArray– Makes it possible to create procedures that receive a variable

number of arguments

– You can not use ParamArray with a multidimensional array

– You can not use ByRef with ParamArray

– All arguments passed to the ParamArray array must be of the same type as the array

2002 Prentice Hall.All rights reserved.

Outline55

ParamArrayTest.vb

1 ' Fig. 7.18: ParamArrayTest.vb2 ' Using ParamArray to create variable-length parameter lists.3 4 Module modParamArrayTest5 6 Sub Main()7 AnyNumberArguments()8 AnyNumberArguments(2, 3)9 AnyNumberArguments(7, 8, 9, 10, 11, 12)10 11 End Sub ' Main12 13 ' receives any number of arguments in array14 Sub AnyNumberArguments(ByVal ParamArray array1 _15 As Integer())16 17 Dim i, total As Integer18 total = 019 20 If array1.Length = 0 Then21 Console.WriteLine("Procedure AnyNumberArguments" & _22 " received 0 arguments.")23 Else24 Console.Write("The total of ")25 26 For i = 0 To array1.GetUpperBound(0)27 Console.Write(array1(i) & " ")28 total += array1(i)29 Next30 31 Console.WriteLine("is {0}.", total)32 End If33

Determines whether or not zero arguments where passed, if not displays array1’s elements and their sum

Applies keyword ParamArray to array1

Calls procedure AnyNumberArguments, passing a different number of arguments each time

2002 Prentice Hall.All rights reserved.

Outline56

ParamArrayTest.vb

34 End Sub ' AnyNumberArguments35 36 End Module ' modParamArrayTest

Procedure AnyNumberArguments received 0 arguments.The total of 2 3 is 5.The total of 7 8 9 10 11 12 is 57.

2002 Prentice Hall. All rights reserved.

57

7.11 For Each/Next Repetition Structure

• For Each/Next– Provided to iterate through the values in a data structure,

such as an array

– Instead of a counter, For Each/Next uses a variable to represent the value of each element

– Useful when the indices of the elements are not important

– Particularly useful for looping through arrays of objects

2002 Prentice Hall.All rights reserved.

Outline58

ForEach.vb

1 ' Fig. 7.19: ForEach.vb2 ' Program uses For Each/Next to find a minimum grade.3 4 Module modForEach5 6 Sub Main()7 Dim gradeArray As Integer(,) = New Integer(,) _8 {{77, 68, 86, 73}, {98, 87, 89, 81}, {70, 90, 86, 81}}9 10 Dim grade As Integer11 Dim lowGrade As Integer = 10012 13 For Each grade In gradeArray14 15 If grade < lowGrade Then16 lowGrade = grade17 End If18 19 Next20 21 Console.WriteLine("The minimum grade is: {0}", lowGrade)22 End Sub ' Main23 24 End Module ' modForEach

The minimum grade is: 68

Specifies a variable grade and an array gradeArray. The structure iterates through all the elements in gradeArray, sequentially assigning

each value to variable grade

The values are compared to variable lowGrade, which stores the lowest grade in the array