1 Chapter 7 - Arrays Outline 7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9 7.10 7.11 Introduction Arrays Declaring and Allocating Arrays 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 Passing Arrays to Procedures Passing Arrays: ByVal vs. ByRef Sorting Arrays 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 Multidimensional Rectangular and Jagged Arrays Variable-Length Parameter Lists 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 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 Fig. 7.1 2002 Prentice Hall. All rights reserved. numberArray(0) -45 numberArray(1) 6 numberArray(2) 0 numberArray(3) 72 numberArray(4) 1543 numberArray(5) -89 numberArray(6) 0 numberArray(7) 62 numberArray(8) -3 numberArray(9) 1 numberArray(10) 6453 numberArray(11) 78 Array consisting of 12 elements. 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. 7 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 ' Fig. 7.2: CreateArray.vb ' Declaring and allocating an array. Imports System.Windows.Forms Outline CreateArray.vb Module modCreateArray Sub Main()A variable capable of storing a reference to Allocateelements an array of 10 elements an array of Integer Dim output As String Dim i As Integer using New and assigns it to array Appends to output the headings for As the Integer() ' declare array variable columns For displayed by the program structure is used to append Dim array array = New Integer(9) {} ' allocate memory for array output &= "Subscript " the index number and value of &each vbTab & "Value" array element &to vbCrLf output ' display values in array For i = 0 To array.GetUpperBound(0) The length property returns the output &= i & vbTab array(i) vbCrLf number& of elements& in the array Next output &= vbCrLf & "The array contains " & _ array.Length & " elements." MessageBox.Show(output, "Array of Integer Values", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main End Module ' modCreateArray 2002 Prentice Hall. All rights reserved. 8 7.4 Examples Using Arrays Outline CreateArray.vb 2002 Prentice Hall. All rights reserved. 9 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline ' Fig. 7.3: InitArray.vb ' Initializing arrays. Imports System.Windows.Forms InitArray.vb Module modInitArray One statement is used to declare the two arrays Sub Main() Dim output As String Dim i As Integer array1 with Allocates array2, whose size is determined New andbyinitialize the values in the array, ' initializer list specifies number of elements arry1.GetUpperBound(0), so that array1 using an initializer list ' and value of each element andarray1 array2 have the same {32, upper27, bound = New Integer() 64, 18, 95, _ Allocates the 10two elements of Dim array1, array2 As Integer() ' declare arrays 14, 90, 70, 60, 37} Initializes each element in array2 to the even integers based on length of array1 ' allocate array2 array2 = New Integer(array1.GetUpperBound(0)) {} ' set values in array2 by a calculation For i = 0 To array2.GetUpperBound(0) array2(i) 2 + 2in*the i arrays to Uses the =values Next build String output, which is &= displayed in a MessageBox output "Subscript " & vbTab & "Array1" & vbTab & _ "Array2" & vbCrLf ' display values for both arrays For i = 0 To array1.GetUpperBound(0) output &= i & vbTab & array1(i) & vbTab & array2(i) & _ vbCrLf Next 2002 Prentice Hall. All rights reserved. 10 36 37 38 39 40 MessageBox.Show(output, "Array of Integer Values", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main End Module ' modInitArray Outline InitArray.vb 2002 Prentice Hall. All rights reserved. 11 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ' Fig. 7.4: SumArray.vb ' Computing sum of elements in array. Declares, allocates and initializes the 10-element array, array Imports System.Windows.Forms Outline SumArray.vb Module modSumArray Sub Main() Dim array As Integer() = New Integer() _ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Performs the addition Dim total As Integer = 0, i As Integer = 0 ' sum array element values For i = 0 To array.GetUpperBound(0) total += array(i) Next MessageBox.Show("Total of array elements: " & total, _ "Sum the elements of an Array", MessageBoxButtons.OK, _ MessageBoxIcon.Information) End Sub ' Main End Module ' modSumArray 2002 Prentice Hall. All rights reserved. 12 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' Fig. 7.5: StudentPoll.vb ' Using arrays to display poll results. Imports System.Windows.Forms Outline StudentPoll.vb Module modStudentPoll Array responses is a 40-element Sub Main() integer array containing the student’s Dim answer, rating As Integer responses theString survey Dim outputto As ' student response array (typically input at run time) Dim responses As Integer() Reads the responses the8, array responses = New Integer() {1, 2,from 6, 4, 5, responses 9, 7, _ 8, 10, 1, 6, 3, 10, and 3, increments 8, 2, 7, 6, 5,of7,the 6,10_ one8,at 6, a time one 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10} counters in the frequency array ' response frequency array (indices 0 through 10) Dim frequency As Integer() = New Integer(10) {} ' count frequencies For answer = 0 To responses.GetUpperBound(0) frequency(responses(answer)) += 1 Next output &= "Rating " & vbTab & "Frequency " & vbCrLf For rating = 1 To frequency.GetUpperBound(0) output &= rating & vbTab & frequency(rating) & vbCrLf Next 2002 Prentice Hall. All rights reserved. 13 32 33 34 35 36 MessageBox.Show(output, "Student Poll Program", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main End Module ' modStudentPoll Outline StudentPoll.vb 2002 Prentice Hall. All rights reserved. 14 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 ' Fig. 7.6: Histogram.vb ' Using data to create histograms. Imports System.Windows.Forms Outline Histogram.vb Module modHistogram Sub Main() Dim output As String Dim i, j As Integer ' output string ' counters ' create data array Nested For loops append the bars to Dim array1 As Integer() = New Integer() _ the String that is displayed {19, 3, 15, 7, 11, 9, 13, 5, 17, 1}in the MessageBox output &= "Element " & vbTab & "Value " & vbTab & _ "Histogram" Inner For structure counts from 1 to array(i), which is the value For i = 0 To array1.GetUpperBound(0) ithvbTab index &ofarray1(i) array1 & vbTab output &= vbCrLfin&the i & For j = 1 To array1(i) output &= "*" ' add one asterisk Next Next MessageBox.show(output, "Histogram Printing Program", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main End Module ' modHistogram 2002 Prentice Hall. All rights reserved. 15 Outline Histogram.vb 2002 Prentice Hall. All rights reserved. 16 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 received 2002 Prentice Hall. All rights reserved. 17 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ' Fig. 7.8: PassArray.vb ' Passing arrays and individual array elements to procedures. Imports System.Windows.Forms Outline PassArray.vb Module modPassArray Dim output As String Sub Main() Dim array1 As Integer() = New Integer() {1, 2, 3, 4, 5} Dim i As Integer Appends five elements of output the = "EFFECTS OF PASSING ENTIRE ARRAY array1 String output "BYtoREFERENCE:" & vbCrLf & vbCrLf & _ " & _ "The values of the original array are:" & vbCrLf ' display original elements of array1 Passes array1 to procedure For i = 0 To array1.GetUpperBound(0) ModifyArray output &= " " & array1(i) Next ModifyArray(array1) ' array is passed by reference output &= vbCrLf & _ Appends the elements of "The values of the modified are:" & vbCrLf array1 array to output ' display modified elements of array1 For i = 0 To array1.GetUpperBound(0) output &= " " & array1(i) Next 2002 Prentice Hall. All rights reserved. 18 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 output &= vbCrLf & vbCrLf & _ "EFFECTS OF PASSING ARRAY ELEMENT " & _ "BY VALUE:" & vbCrLf & vbCrLf & "array1(3) " & _ "before ModifyElementByVal: " & array1(3) Outline PassArray.vb ' array element passed by value ModifyElementByVal(array1(3)) output &= vbCrLf & "array1(3) after " & _ "ModifyElementByVal: " & array1(3) output &= vbCrLf & vbCrLf & "EFFECTS OF PASSING " & _ "ARRAY ELEMENT BY REFERENCE: " & vbCrLf & vbCrLf & _ "array1(3) before ModifyElementByRef: " & array1(3) ' array element passed by reference ModifyElementByRef(array1(3)) output &= vbCrLf & "array1(3) after " & _ "ModifyElementByRef: " & array1(3) Multiplies the elements of MessageBox.Show(output, "Passing Arrays", _ arrayParameter by 2 MessageBoxIcon.Information) MessageBoxButtons.OK, End Sub ' Main ' procedure modifies array it receives (note ByVal) Sub ModifyArray(ByVal arrayParameter As Integer()) Dim j As Integer For j = 0 To arrayParameter.GetUpperBound(0) arrayParameter(j) *= 2 Next End Sub ' ModifyArray 2002 Prentice Hall. All rights reserved. 19 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 ' procedure modifies integer passed to it ' original is not be modified (note ByVal) Sub ModifyElementByVal(ByVal element As Integer) output &= vbCrLf & "Value "ModifyElementByVal: " element *= 2 output &= vbCrLf & "Value "ModifyElementByVal: " End Sub ' ModifyElementByVal received in " & _ & element Outline PassArray.vb calculated in " & _ & element ' procedure modifies integer passed to it ' original is be modified (note ByRef) Sub ModifyElementByRef(ByRef element As Integer) output &= vbCrLf & "Value "ModifyElementByRef: " element *= 2 output &= vbCrLf & "Value "ModifyElementByRef: " End Sub ' ModifyElementByRef received in " & _ & element calculated in " & _ & element End Module ' modPassArray 2002 Prentice Hall. All rights reserved. 20 Outline PassArray.vb 2002 Prentice Hall. All rights reserved. 21 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. 22 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. 23 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 ' Fig. 7.9: ArrayReferenceTest.vb ' Testing the effects of passing array references using ' ByVal and ByRef. Module modArrayReferenceTest Outline ArrayReferenceTe st.vb Sub Main() Dim i As Integer Copies reference firstArray to ' declare array references variable firstArrayCopy, now Dim firstArray As Integer() they reference the same object Dim firstArrayCopy As Integer() ' allocate firstArray and copy its reference firstArray = New Integer() {1, 2, 3} firstArrayCopy = firstArray Console.WriteLine("Test passing array reference " & _ "using ByVal.") Prints contents first to verify that FirstDouble Console.Write("Contents of indeed firstArray before " & _ contents changes the array’s "calling FirstDouble: ") ' print contents of firstArray For i = 0 To firstArray.GetUpperBound(0) Console.Write(firstArray(i) & " ") firstArray is passed to Next FirstDouble ' pass firstArray using ByVal FirstDouble(firstArray) Console.Write(vbCrLf & "Contents of firstArray after " & _ "calling FirstDouble: ") 2002 Prentice Hall. All rights reserved. 24 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 ' references print contents of firstArray Compares firstArray For i = 0 To firstArray.GetUpperBound(0) and firstArrayCopy Console.Write(firstArray(i) & " ") Next ' test whether reference was changed by FirstDouble If firstArray Is firstArrayCopy Then Console.WriteLine(vbCrLf & "The references are " & _ "equal.") Else Console.WriteLine(vbCrLf & "The references are " & _ "not equal.") End If Outline ArrayReferenceTe st.vb ' declare array references Dim secondArray As Integer() Dim secondArrayCopy As Integer() ' allocate secondArray and copy its reference secondArray = New Integer() {1, 2, 3} secondArrayCopy = secondArray Console.WriteLine(vbCrLf & "Test passing array " & _ "reference using ByRef.") Console.Write("Contents of secondArray before " & _ "calling SecondDouble: ") ' print contents of secondArray before procedure call For i = 0 To secondArray.GetUpperBound(0) Console.Write(secondArray(i) & " ") Next ' pass secondArray using ByRef SecondDouble(secondArray) 2002 Prentice Hall. All rights reserved. 25 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 Outline Console.Write(vbCrLf & "Contents of secondArray " & _ "after calling SecondDouble: ") ' print contents of secondArray after procedure call For i = 0 To secondArray.GetUpperBound(0) Console.Write(secondArray(i) & " ") Next ArrayReferenceTe st.vb ' test whether the reference was changed by SecondDouble If secondArray Is secondArrayCopy Then Console.WriteLine(vbCrLf & "The references are " & _ "equal.") Else Console.WriteLine(vbCrLf & "The references are " & _ "not equal.") End If End Sub ' Main Reference is passed ByVal ' procedure modifies elements of array and assigns ' new reference (note ByVal) Sub FirstDouble(ByVal array As Integer()) Dim i As Integer Multiplies all the elements of the array by 2 ' double each element value new array, and attempts to assign it’s reference to parameter For Allocates i = 0 To aarray.GetUpperBound(0) array(i) *= 2 array, attempting to overwrite reference firstArray in memory, but Next will fail because the reference was passed ByVal ' create new reference and assign it to array array = New Integer() {11, 12, 13} End Sub ' FirstDouble 2002 Prentice Hall. All rights reserved. Reference is passed ByRef 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 ' procedure modifies elements of array and assigns ' new reference (note ByRef) Sub SecondDouble(ByRef array As Integer()) Dim i As Integer Because the reference was passed with ByRef, the called ' double contents of array For i =procedure 0 To array.GetUpperBound(0) has the ability to modify what the reference array(i) *= 2 actually points to Next 26 Outline ArrayReferenceTe st.vb ' create new reference and assign it to array array = New Integer() {11, 12, 13} End Sub ' SecondDouble End Module ' modPassArray Test passing 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. Test passing 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. 2002 Prentice Hall. All rights reserved. 27 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. 28 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Outline ' Fig. 7.10: BubbleSort.vb ' Procedures for sorting an integer array. Sorts the elements of it’s parameter sortArray Module modBubbleSort ' sort array using bubble sort algorithm The nested performs sortArraystructure As Integer()) This Sub innerBubbleSort(ByVal loop controls the For/Next comparisons Dim pass, i As Integer BubbleSort.vb the sort and swapping, if necessary, of the elements For during pass =each 1 Topass sortArray.GetUpperBound(0) For i = 0 To sortArray.GetUpperBound(0) - 1 If sortArray(i) > sortArray(i + 1) Then Swap(sortArray, i) End If Next Next Gets called by BubbleSort to End Subtwo ' BubbleSort transpose of the array elements ' swap two array elements Sub Swap(ByVal swapArray As Integer(), _ ByVal first As Integer) Dim hold As Integer hold = swapArray(first) swapArray(first) = swapArray(first + 1) swapArray(first + 1) = hold End Sub ' Swap End Module ' modBubbleSort 2002 Prentice Hall. All rights reserved. 29 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 ' Fig. 7.11: BubbleSortTest.vb ' Program creates random numbers and sorts them. Imports System.Windows.Forms Public Class FrmBubbleSort Inherits System.Windows.Forms.Form Outline BubbleSortTest.v b ' buttons Friend WithEvents cmdCreate As Button Friend WithEvents cmdSort As Button ' labels Friend WithEvents lblOriginal As Label Friend WithEvents lblSorted As Label ' textboxes Friend WithEvents txtOriginal As TextBox Friend WithEvents txtSorted As TextBox ' Visual Studio .NET generated code Dim array As Integer() = New Integer(9) {} ' creates random generated numbers Private Sub cmdCreate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdCreate.Click Dim output As String Dim randomNumber As Random = New Random() Dim i As Integer txtSorted.Text = "" 2002 Prentice Hall. All rights reserved. 30 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 ' create 10 random numbers and append to output For i = 0 To array.GetUpperBound(0) array(i) = randomNumber.Next(100) output &= array(i) & vbCrLf Next Outline BubbleSortTest.v b txtOriginal.Text = output ' display numbers cmdSort.Enabled = True ' enables cmdSort button End Sub ' cmdCreate_Click ' sorts randomly generated numbers Private Sub cmdSort_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdSort.Click Dim output As String Dim i As Integer ' sort array modBubbleSort.BubbleSort(array) ' creates string with sorted numbers For i = 0 To array.GetUpperBound(0) output &= array(i) & vbCrLf Next txtSorted.Text = output ' display numbers cmdSort.Enabled = False End Sub ' cmdSort_Click End Class ' FrmBubbleSort 2002 Prentice Hall. All rights reserved. 31 Outline BubbleSortTest.v b 2002 Prentice Hall. All rights reserved. 32 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. 33 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ' Fig. 7.12: LinearSearch.vb ' Linear search of an array. Module modLinearSearch Outline LinearSearch.vb ' iterates through array Function LinearSearch(ByVal key As Integer, _ ByVal Compares eachnumbers elementAs of Integer()) the array As Integer with a search key Dim n As Integer ' structure iterates linearly through array For n = 0 To numbers.GetUpperBound(0) If numbers(n) = key Then If the search key is notnfound, the procedure Return End aIf returns –1, non-valid index number Next Return -1 End Function ' LinearSearch End Module ' modLinearSearch 2002 Prentice Hall. All rights reserved. 34 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 ' Fig. 7.13: LinearSearchTest.vb ' Linear search of an array. Imports System.Windows.Forms Public Class FrmLinearSearchTest Inherits System.Windows.Forms.Form Outline LinearSearchTest .vb ' buttons Friend WithEvents cmdSearch As Button Friend WithEvents cmdCreate As Button ' text boxes Friend WithEvents txtInput As TextBox Friend WithEvents txtData As TextBox ' labels Friend WithEvents lblEnter As Label Friend WithEvents lblResult As Label ' Visual Studio .NET generated code Dim array1 As Integer() = New Integer(19) {} ' creates random data Private Sub cmdCreate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdCreate.Click Dim output As String Dim randomNumber As Random = New Random() Dim i As Integer output = "Index" & vbTab & "Value" & vbCrLf 2002 Prentice Hall. All rights reserved. 35 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 ' creates string containing 11 random numbers For i = 0 To array1.GetUpperBound(0) array1(i) = randomNumber.Next(1000) output &= i & vbTab & array1(i) & vbCrLf Next Outline LinearSearchTest .vb txtData.Text = output ' displays numbers txtInput.Text = "" ' clear search key text box cmdSearch.Enabled = True ' enable search button End Sub ' cmdCreate_Click ' searches key of element Private Sub cmdSearch_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdSearch.Click ' if search key text box is empty, display ' message and exit procedure If txtInput.Text = "" Then MessageBox.Show("You must enter a search key.") Exit Sub End If Dim searchKey As Integer = Convert.ToInt32(txtInput.Text) Dim element As Integer = LinearSearch(searchKey, array1) If element <> -1 Then lblResult.Text = "Found Value in index " & element Else lblResult.Text = "Value Not Found" End If End Sub ' cmdSearch_Click End Class ' FrmLinearSearch 2002 Prentice Hall. All rights reserved. 36 Outline LinearSearchTest .vb 2002 Prentice Hall. All rights reserved. 37 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 ' Fig. 7.14: BinarySearchTest.vb ' Demonstrating binary search of an array. Imports System.Windows.Forms Public Class FrmBinarySearch Inherits System.Windows.Forms.Form ' labels Friend WithEvents Friend WithEvents Friend WithEvents Friend WithEvents Friend WithEvents Friend WithEvents Outline BinarySearchTest .vb lblEnterKey As Label lblResult As Label lblResultOutput As Label lblDisplay As Label lblIndex As Label lblIndexes As Label ' button Friend WithEvents cmdFindKey As Button ' text box Friend WithEvents txtInput As TextBox ' Visual Studio .NET generated code Dim array1 As Integer() = New Integer(14) {} ' FrmBinarySearch initializes array1 to ascending values ' 0, 2, 4, 6, ..., 28 when first loaded Private Sub FrmBinarySearch_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim i As Integer 2002 Prentice Hall. All rights reserved. 38 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 For i = 0 To array1.GetUpperBound(0) array1(i) = 2 * i Next End Sub ' FrmBinarySearch_Load Outline BinarySearchTest .vb ' event handler for cmdFindKey button Private Sub cmdFindKey_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdFindKey.Click Dim searchKey As Integer = Convert.ToInt32(txtInput.Text) lblDisplay.Text = "" ' perform binary search Dim element As Integer = BinarySearch(array1, searchKey) If element <> -1 Then lblResultOutput.Text = "Found value in element " & element Else lblResultOutput.Text = "Value not found" Receives End Iftwo arguments, the array to search, and the search key End Sub ' cmdFindKey_Click ' performs binary search Function BinarySearch(ByVal array As Integer(), _ ByVal key As Integer) As Integer Dim low As Integer = 0 ' low index Dim high As Integer = array.GetUpperBound(0) ' high index Dim middle As Integer ' middle index 2002 Prentice Hall. All rights reserved. 39 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 While low <= high middle = (low + high) \ 2 ' the following line displays part ' of array being of manipulated during Calculates thethe middle element thekey, array If middle matches then ' each iteration of loop middle is returned BuildOutput(low, middle, high) Outline BinarySearchTest .vb If key = array(middle) Then ' match Return middle ElseIf key < array(middle) Then ' search low end high = middle - 1 ' of array Else low = middle + 1 End If If key does End While not match middle, then the low or high index is adjusted so that a smaller subarray can be searched Return -1 ' search key not found End Function ' BinarySearch Sub BuildOutput(ByVal low As Integer, _ ByVal middle As Integer, ByVal high As Integer) Dim i As Integer 2002 Prentice Hall. All rights reserved. 40 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 For i = 0 To array1.GetUpperBound(0) If i < low OrElse i > high Then lblDisplay.Text &= " " ElseIf i = middle Then ' mark middle element in output lblDisplay.Text &= String.Format("{0:D2}", _ array1(i)) & "* " Else lblDisplay.Text &= String.Format("{0:D2}", _ array1(i)) & " " End If Outline BinarySearchTest .vb Next i lblDisplay.Text &= vbCrLf End Sub ' BuildOutput End Class ' FrmBinarySearch 2002 Prentice Hall. All rights reserved. 41 Outline BinarySearchTest .vb 2002 Prentice Hall. All rights reserved. 42 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. 43 7.9 Multidimensional Rectangular and Jagged Arrays Column 0 Column 1 Column 2 Column 3 Row 0 a(0, 0) a(0, 1) a(0, 2) a(0, 3) Row 1 a(1, 0) a(1, 1) a(1, 2) a(1, 3) Row 2 a(2, 0) a(2, 1) a(2, 2) a(2, 3) Column index Row index (or subscript) Array name Fig. 7.15 Two-dimensional array with three rows and four columns. 2002 Prentice Hall. All rights reserved. 44 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 ' Fig. 7.16: MultidimensionalArrays.vb ' Initializing multi-dimensional arrays. Imports System.Windows.Forms Module modMultidimensionalArrays Outline Multidimensional Arrays.vb Sub Main() Dim output As String Dim i, j As Integer Allocates array1 with six initializers in two sublists ' create rectangular two-dimensional array The declaration and allocation of array2 Dim array1 As Integer(,) creates a jagged array of 3 arrays array1 = New Integer(,) {{1, 2, 3}, {4, 5, 6}} ' create jagged two-dimensional array Dim array2 As Integer()() = New Integer(2)() {} array2(0) = New Integer() {1, 2} array2(1) New in Integer() {3} Traverses the=array two dimensions array2(2) = New Integer() {4, 5, 6} output = "Values in array1 by row are " & vbCrLf For i = 0 To array1.GetUpperBound(0) For j = 0 To array1.GetUpperBound(1) output &= array1(i, j) & " " Next output &= vbCrLf Next 2002 Prentice Hall. All rights reserved. 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 In a jagged two-dimensional array, the second dimension is output &= vbCrLf & "Values in array2 by row are " & actually the first dimension of a separate array vbCrLf For i = 0 To array2.GetUpperBound(0) For j = 0 To array2(i).GetUpperBound(0) output &= array2(i)(j) & " " Next 45 _ Outline Multidimensional Arrays.vb output &= vbCrLf Next MessageBox.Show(output, _ "Initializing Multi-Dimensional Arrays", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main End Module ' modMultidimensionalArrays 2002 Prentice Hall. All rights reserved. 46 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 Outline ' Fig 7.17: JaggedArray.vb ' Jagged two-dimensional array example. Imports System.Windows.Forms JaggedArray.vb Module modJaggedArray Dim lastStudent, lastExam As Integer Dim output As String Sub Main() Dim i As Integer ' jagged array with 3 rows of exam scores Dim gradeArray As Integer()() = New Integer(2)() {} ' allocate each gradeArray(0) = gradeArray(1) = gradeArray(2) = row New New New with 4 student Integer() {77, Integer() {98, Integer() {70, grades 68, 86, 73} 87, 89, 81} 90, 86, 81} ' upper bounds for array manipulations lastStudent = gradeArray.GetUpperBound(0) lastExam = gradeArray(0).GetUpperBound(0) output = "Students \ Exams" & vbCrLf ' build output string BuildString(gradeArray) output &= vbCrLf & vbCrLf & "Lowest grade: " & _ Minimum(gradeArray) & vbCrLf & "Highest grade: " & _ Maximum(gradeArray) & vbCrLf 2002 Prentice Hall. All rights reserved. 47 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 ' calculate each student's average For i = 0 To lastStudent output &= vbCrLf & "Average for student " & _ i & " is " & Average(gradeArray(i)) Next Outline JaggedArray.vb MessageBox.Show(output, "Jagged two-dimensional array", _ MessageBoxIcon.Information) Determines MessageBoxButtons.OK, the lowest grade of any student for the semester End Sub ' Main ' find minimum grade Function Minimum(ByVal grades As Integer()()) _ As Integer Dim lowGrade As Integer = 100 Dim i, j As Integer For i = 0 To lastStudent For j = 0 To lastExam If grades(i)(j) < lowGrade Then lowGrade = grades(i)(j) End If Next Next Return lowGrade End Function ' Minimum 2002 Prentice Hall. All rights reserved. 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 ' find the maximum grade Function Maximum(ByVal grades As Integer()()) _ As Integer Dim highGrade As Integer = 0 Dim i, j As Integer 48 Outline JaggedArray.vb Determines the highest grade of any student for the semester For i = 0 To lastStudent For j = 0 To lastExam If grades(i)(j) > highGrade Then highGrade = grades(i)(j) End If Next Next Determines a particular student’s semester average Return highGrade End Function ' Maximum ' determine the average grade for student ' (or set of grades) Function Average(ByVal setOfGrades As Integer()) _ As Double Dim i As Integer, total As Integer = 0 ' find sum of student's grades For i = 0 To lastExam total += setOfGrades(i) Next Return total / setOfGrades.Length End Function ' Average 2002 Prentice Hall. All rights reserved. 49 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 ' creates String displaying array Sub BuildString(ByVal grades As Integer()()) Dim i, j As Integer Outline JaggedArray.vb ' align column heads output &= " " Appends the two dimensional array to For i = 0 To lastExam string output output &= "("in&tabular i & ")format " Next For i = 0 To lastStudent output &= vbCrLf & " (" & i & ") For j = 0 To lastExam output &= grades(i)(j) & " Next " " Next End Sub ' BuildString End Module ' modJaggedArray 2002 Prentice Hall. All rights reserved. 50 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. 51 1 ' Fig. 7.18: ParamArrayTest.vb 2 ' Calls Usingprocedure ParamArray to create variable-length parameter lists. AnyNumberArguments, passing a 3 different number of arguments each time 4 Module modParamArrayTest 5 6 Sub Main() 7 AnyNumberArguments() 8 AnyNumberArguments(2, 3) 9 AnyNumberArguments(7, 8, 9, 10, 11, 12) Applies keyword ParamArray to array1 10 11 End Sub ' Main 12 13 ' receives any number of arguments in array 14 Sub AnyNumberArguments(ByVal ParamArray array1 _ 15DeterminesAswhether Integer()) or not zero arguments where passed, if 16 not displays array1’s elements and their sum 17 Dim i, total As Integer 18 total = 0 19 20 If array1.Length = 0 Then 21 Console.WriteLine("Procedure AnyNumberArguments" & _ 22 " received 0 arguments.") 23 Else 24 Console.Write("The total of ") 25 26 For i = 0 To array1.GetUpperBound(0) 27 Console.Write(array1(i) & " ") 28 total += array1(i) 29 Next 30 31 Console.WriteLine("is {0}.", total) 32 End If 33 Outline ParamArrayTest.v b 2002 Prentice Hall. All rights reserved. 52 34 35 36 End Sub ' AnyNumberArguments Outline 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. ParamArrayTest.v b 2002 Prentice Hall. All rights reserved. 53 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. 54 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ' Fig. 7.19: ForEach.vb ' Program uses For Each/Next to find a minimum grade. Module modForEach Outline ForEach.vb Sub Main() Specifies a variable grade and an array gradeArray. The structure Dim gradeArray As Integer(,) = New Integer(,) _ iterates{{77, through all86, the 73}, elements gradeArray, sequentially 68, {98,in87, 89, 81}, {70, 90, 86, 81}} assigning each value to variable grade Dim grade As Integer Dim lowGrade As Integer = 100 to The values are compared For Each variable lowGrade, whichInstores the lowest grade in the array grade gradeArray If grade < lowGrade Then lowGrade = grade End If Next Console.WriteLine("The minimum grade is: {0}", lowGrade) End Sub ' Main End Module ' modForEach The minimum grade is: 68 2002 Prentice Hall. All rights reserved.