540 likes | 548 Views
Learn about declaring, allocating, initializing arrays, passing arrays to procedures, sorting, searching, and multidimensional arrays in Visual Basic. Master array manipulation techniques in Visual Basic with comprehensive examples.
E N D
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:ByValvs.ByRef7.7 Sorting Arrays7.8 Searching Arrays: Linear Search and Binary Search7.8.1 Searching an Array with Linear Search7.8.2 Searching a Sorted Array with Binary Search7.9 Multidimensional Rectangular and Jagged Arrays7.10 Variable-Length Parameter Lists7.11 ForEach/NextRepetition Structure
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
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
7.2 Arrays Name of array (note that all elements of this array have the same name, numberArray) 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 Position number (index or subscript) of the element within array numberArray numberArray(10) 6453 78 numberArray(11) Fig. 7.1 Array consisting of 12 elements.
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
7.4 Examples Using Arrays • Several examples that demonstrate • Declaration • Allocation • Initialization of arrays
A variable capable of storing a reference to an array of Integer elements Allocate an array of 10 elements using New and assigns it to array Appends to output the headings for the columns displayed by the program For 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 1 ' Fig. 7.2: CreateArray.vb 2 ' Declaring and allocating an array. 3 4 Imports System.Windows.Forms 5 6 Module modCreateArray 7 8 Sub Main() 9 Dim output As String 10 Dim i As Integer 11 12Dim arrayAs Integer() ' declare array variable 13 array = New Integer(9) {} ' allocate memory for array 14 15 output &= "Subscript " & vbTab & "Value" & vbCrLf 16 17 ' display values in array 18For i = 0To array.GetUpperBound(0) 19 output &= i & vbTab & array(i) & vbCrLf 20 Next 21 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 ' Main 28 29 End Module' modCreateArray CreateArray.vb
7.4 Examples Using Arrays CreateArray.vb
One statement is used to declare the two arrays Allocates the 10 elements of array1 with New and initialize the values in the array, using an initializer list Allocates array2, whose size is determined by arry1.GetUpperBound(0), so that array1 and array2 have the same upper bound Initializes each element in array2 to the even integers Uses the values in the arrays to build String output, which is displayed in a MessageBox 1 ' Fig. 7.3: InitArray.vb 2 ' Initializing arrays. 3 4 Imports System.Windows.Forms 5 6 Module modInitArray 7 8 Sub Main() 9 Dim output As String 10 Dim i As Integer 11 12Dim array1, array2 As Integer() ' declare two arrays 13 14 ' initializer list specifies number of elements 15 ' and value of each element 16 array1 = NewInteger() {32, 27, 64, 18, 95, _ 17 14, 90, 70, 60, 37} 18 19 ' allocate array2 based on length of array1 20 array2 = NewInteger(array1.GetUpperBound(0)) {} 21 22 ' set values in array2 by a calculation 23For i = 0To array2.GetUpperBound(0) 24 array2(i) = 2 + 2 * i 25 Next 26 27 output &= "Subscript " & vbTab & "Array1" & vbTab & _ 28 "Array2" & vbCrLf 29 30 ' display values for both arrays 31For i = 0To array1.GetUpperBound(0) 32 output &= i & vbTab & array1(i) & vbTab & array2(i) & _ 33 vbCrLf 34 Next 35 InitArray.vb
36 MessageBox.Show(output, "Array of Integer Values", _ 37 MessageBoxButtons.OK, MessageBoxIcon.Information) 38 End Sub' Main 39 40 End Module' modInitArray InitArray.vb
Declares, allocates and initializes the 10-element array, array Performs the addition 1 ' Fig. 7.4: SumArray.vb 2 ' Computing sum of elements in array. 3 4 Imports System.Windows.Forms 5 6 Module modSumArray 7 8 SubMain() 9Dim array AsInteger() = NewInteger() _ 10 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 11 12 Dim total AsInteger = 0, i AsInteger = 0 13 14 ' sum array element values 15 For i = 0To array.GetUpperBound(0) 16 total += array(i) 17 Next 18 19 MessageBox.Show("Total of array elements: " & total, _ 20 "Sum the elements of an Array", MessageBoxButtons.OK, _ 21 MessageBoxIcon.Information) 22 EndSub ' Main 23 24 EndModule ' modSumArray SumArray.vb
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 1 ' Fig. 7.5: StudentPoll.vb 2 ' Using arrays to display poll results. 3 4 Imports System.Windows.Forms 5 6 Module modStudentPoll 7 8 Sub Main() 9 Dim answer, rating AsInteger 10 Dim output AsString 11 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 frequencies 22For answer = 0To responses.GetUpperBound(0) 23 frequency(responses(answer)) += 1 24 Next 25 26 output &= "Rating " & vbTab & "Frequency " & vbCrLf 27 28 For rating = 1To frequency.GetUpperBound(0) 29 output &= rating & vbTab & frequency(rating) & vbCrLf 30 Next 31 StudentPoll.vb
32 MessageBox.Show(output, "Student Poll Program", _ 33 MessageBoxButtons.OK, MessageBoxIcon.Information) 34 End Sub ' Main 35 36 End Module' modStudentPoll StudentPoll.vb
Nested For loops append the bars to the String that is displayed in the MessageBox Inner For structure counts from 1 to array(i), which is the value in the ith index of array1 1 ' Fig. 7.6: Histogram.vb 2 ' Using data to create histograms. 3 4 Imports System.Windows.Forms 5 6 Module modHistogram 7 8 Sub Main() 9 Dim output AsString ' output string 10 Dim i, j AsInteger ' counters 11 12 ' create data array 13 Dim array1 AsInteger() = NewInteger() _ 14 {19, 3, 15, 7, 11, 9, 13, 5, 17, 1} 15 16 output &= "Element " & vbTab & "Value " & vbTab & _ 17 "Histogram" 18 19For i = 0To array1.GetUpperBound(0) 20 output &= vbCrLf & i & vbTab & array1(i) & vbTab 21 22For j = 1To array1(i) 23 output &= "*"' add one asterisk 24 Next 25 26 Next 27 28 MessageBox.show(output, "Histogram Printing Program", _ 29 MessageBoxButtons.OK, MessageBoxIcon.Information) 30 End Sub ' Main 31 32 End Module ' modHistogram Histogram.vb
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
Appends the five elements of array1 to String output Passes array1 to procedure ModifyArray Appends the elements of array1 to output 1 ' Fig. 7.8: PassArray.vb 2 ' Passing arrays and individual array elements to procedures. 3 4 Imports System.Windows.Forms 5 6 Module modPassArray 7 Dim output As String 8 9 Sub Main() 10 Dim array1 AsInteger() = NewInteger() {1, 2, 3, 4, 5} 11 Dim i As Integer 12 13 output = "EFFECTS OF PASSING ENTIRE ARRAY " & _ 14 "BY REFERENCE:" & vbCrLf & vbCrLf & _ 15 "The values of the original array are:" & vbCrLf 16 17 ' display original elements of array1 18For i = 0To array1.GetUpperBound(0) 19 output &= " " & array1(i) 20 Next 21 22 ModifyArray(array1) ' array is passed by reference 23 24 output &= vbCrLf & _ 25 "The values of the modified array are:" & vbCrLf 26 27 ' display modified elements of array1 28For i = 0To array1.GetUpperBound(0) 29 output &= " " & array1(i) 30 Next 31 PassArray.vb
Multiplies the elements of arrayParameter by 2 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 value 38 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 reference 48 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 EndSub' Main 56 57 ' procedure modifies array it receives (note ByVal) 58Sub ModifyArray(ByVal arrayParameter AsInteger()) 59 Dim j AsInteger 60 61 For j = 0To arrayParameter.GetUpperBound(0) 62 arrayParameter(j) *= 2 63 Next 64 65 EndSub' ModifyArray 66 PassArray.vb
67 ' procedure modifies integer passed to it 68 ' original is not be modified (note ByVal) 69 Sub ModifyElementByVal(ByVal element AsInteger) 70 71 output &= vbCrLf & "Value received in " & _ 72 "ModifyElementByVal: " & element 73 element *= 2 74 output &= vbCrLf & "Value calculated in " & _ 75 "ModifyElementByVal: " & element 76 EndSub' ModifyElementByVal 77 78 ' procedure modifies integer passed to it 79 ' original is be modified (note ByRef) 80 Sub ModifyElementByRef(ByRef element AsInteger) 81 82 output &= vbCrLf & "Value received in " & _ 83 "ModifyElementByRef: " & element 84 element *= 2 85 output &= vbCrLf & "Value calculated in " & _ 86 "ModifyElementByRef: " & element 87 EndSub' ModifyElementByRef 88 89 EndModule' modPassArray PassArray.vb
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
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
Copies reference firstArray to variable firstArrayCopy, now they reference the same object Prints contents first to verify that FirstDouble indeed changes the array’s contents firstArray is passed to FirstDouble 1 ' Fig. 7.9: ArrayReferenceTest.vb 2 ' Testing the effects of passing array references using 3 ' ByVal and ByRef. 4 5 Module modArrayReferenceTest 6 7 Sub Main() 8 Dim i As Integer 9 10 ' declare array references 11 Dim firstArray As Integer() 12 Dim firstArrayCopy As Integer() 13 14 ' allocate firstArray and copy its reference 15 firstArray = New Integer() {1, 2, 3} 16 firstArrayCopy = firstArray 17 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 firstArray 24For i = 0To firstArray.GetUpperBound(0) 25 Console.Write(firstArray(i) & " ") 26 Next 27 28 ' pass firstArray using ByVal 29 FirstDouble(firstArray) 30 31 Console.Write(vbCrLf & "Contents of firstArray after " & _ 32 "calling FirstDouble: ") 33 ArrayReferenceTest.vb
Compares references firstArray and firstArrayCopy 34 ' print contents of firstArray 35 For i = 0To firstArray.GetUpperBound(0) 36 Console.Write(firstArray(i) & " ") 37 Next 38 39 ' test whether reference was changed by FirstDouble 40If firstArray Is firstArrayCopy Then 41 Console.WriteLine(vbCrLf & "The references are " & _ 42 "equal.") 43 Else 44 Console.WriteLine(vbCrLf & "The references are " & _ 45 "not equal.") 46 End If 47 48 ' declare array references 49 Dim secondArray AsInteger() 50 Dim secondArrayCopy AsInteger() 51 52 ' allocate secondArray and copy its reference 53 secondArray = NewInteger() {1, 2, 3} 54 secondArrayCopy = secondArray 55 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 call 62 For i = 0To secondArray.GetUpperBound(0) 63 Console.Write(secondArray(i) & " ") 64 Next 65 66 ' pass secondArray using ByRef 67 SecondDouble(secondArray) 68 ArrayReferenceTest.vb
Reference is passed ByVal Multiplies all the elements of the array by 2 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 69 Console.Write(vbCrLf & "Contents of secondArray " & _ 70 "after calling SecondDouble: ") 71 72 ' print contents of secondArray after procedure call 73 For i = 0To secondArray.GetUpperBound(0) 74 Console.Write(secondArray(i) & " ") 75 Next 76 77 ' test whether the reference was changed by SecondDouble 78 If secondArray Is secondArrayCopy Then 79 Console.WriteLine(vbCrLf & "The references are " & _ 80 "equal.") 81 Else 82 Console.WriteLine(vbCrLf & "The references are " & _ 83 "not equal.") 84 EndIf 85 86 EndSub' Main 87 88 ' procedure modifies elements of array and assigns 89 ' new reference (note ByVal) 90Sub FirstDouble(ByVal array AsInteger()) 91 Dim i AsInteger 92 93 ' double each element value 94 For i = 0To array.GetUpperBound(0) 95 array(i) *= 2 96 Next 97 98 ' create new reference and assign it to array 99 array = NewInteger() {11, 12, 13} 100 EndSub' FirstDouble 101 ArrayReferenceTest.vb
Reference is passed ByRef Because the reference was passed with ByRef, the called procedure has the ability to modify what the reference actually points to 102 ' procedure modifies elements of array and assigns 103 ' new reference (note ByRef) 104Sub SecondDouble(ByRef array AsInteger()) 105 Dim i AsInteger 106 107 ' double contents of array 108 For i = 0To array.GetUpperBound(0) 109 array(i) *= 2 110 Next 111 112 ' create new reference and assign it to array 113 array = NewInteger() {11, 12, 13} 114 EndSub' SecondDouble 115 116 EndModule' modPassArray ArrayReferenceTest.vb 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.
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
Sorts the elements of it’s parameter sortArray The nested For/Next structure performs the sort This 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 1 ' Fig. 7.10: BubbleSort.vb 2 ' Procedures for sorting an integer array. 3 4 Module modBubbleSort 5 6 ' sort array using bubble sort algorithm 7Sub BubbleSort(ByVal sortArray As Integer()) 8 Dim pass, i As Integer 9 10For pass = 1To sortArray.GetUpperBound(0) 11 12For i = 0To sortArray.GetUpperBound(0) - 1 13 14 If sortArray(i) > sortArray(i + 1) Then 15 Swap(sortArray, i) 16 End If 17 18 Next 19 20 Next 21 22 EndSub' BubbleSort 23 24 ' swap two array elements 25Sub Swap(ByVal swapArray AsInteger(), _ 26 ByVal first AsInteger) 27 28 Dim hold AsInteger 29 30 hold = swapArray(first) 31 swapArray(first) = swapArray(first + 1) 32 swapArray(first + 1) = hold 33 EndSub' Swap 34 35 EndModule' modBubbleSort BubbleSort.vb
1 ' Fig. 7.11: BubbleSortTest.vb 2 ' Program creates random numbers and sorts them. 3 4 Imports System.Windows.Forms 5 6 PublicClass FrmBubbleSort 7 Inherits System.Windows.Forms.Form 8 9 ' buttons 10 FriendWithEvents cmdCreate As Button 11 FriendWithEvents cmdSort As Button 12 13 ' labels 14 FriendWithEvents lblOriginal As Label 15 FriendWithEvents lblSorted As Label 16 17 ' textboxes 18 FriendWithEvents txtOriginal As TextBox 19 FriendWithEvents txtSorted As TextBox 20 21 ' Visual Studio .NET generated code 22 23 Dim array As Integer() = New Integer(9) {} 24 25 ' creates random generated numbers 26 Private Sub cmdCreate_Click(ByVal sender As System.Object, _ 27 ByVal e As System.EventArgs) Handles cmdCreate.Click 28 29 Dim output As String 30 Dim randomNumber As Random = New Random() 31 Dim i AsInteger 32 33 txtSorted.Text = "" 34 BubbleSortTest.vb
35 ' create 10 random numbers and append to output 36 For i = 0To array.GetUpperBound(0) 37 array(i) = randomNumber.Next(100) 38 output &= array(i) & vbCrLf 39 Next 40 41 txtOriginal.Text = output ' display numbers 42 cmdSort.Enabled = True' enables cmdSort button 43 EndSub ' cmdCreate_Click 44 45 ' sorts randomly generated numbers 46 Private Sub cmdSort_Click(ByVal sender As System.Object, _ 47 ByVal e As System.EventArgs) Handles cmdSort.Click 48 49 Dim output As String 50 Dim i As Integer 51 52 ' sort array 53 modBubbleSort.BubbleSort(array) 54 55 ' creates string with sorted numbers 56 For i = 0 To array.GetUpperBound(0) 57 output &= array(i) & vbCrLf 58 Next 59 60 txtSorted.Text = output ' display numbers 61 cmdSort.Enabled = False 62 EndSub' cmdSort_Click 63 64 EndClass' FrmBubbleSort BubbleSortTest.vb
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
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 1 ' Fig. 7.12: LinearSearch.vb 2 ' Linear search of an array. 3 4 Module modLinearSearch 5 6 ' iterates through array 7 Function LinearSearch(ByVal key AsInteger,_ 8 ByVal numbers AsInteger()) AsInteger 9 10 Dim n AsInteger 11 12 ' structure iterates linearly through array 13For n = 0 To numbers.GetUpperBound(0) 14 15 If numbers(n) = key Then 16 17 Return n 18 End If 19 20 Next 21 22Return-1 23 End Function ' LinearSearch 24 25 End Module ' modLinearSearch LinearSearch.vb
1 ' Fig. 7.13: LinearSearchTest.vb 2 ' Linear search of an array. 3 4 Imports System.Windows.Forms 5 6 PublicClass FrmLinearSearchTest 7 Inherits System.Windows.Forms.Form 8 9 ' buttons 10 FriendWithEvents cmdSearch As Button 11 FriendWithEvents cmdCreate As Button 12 13 ' text boxes 14 FriendWithEvents txtInput As TextBox 15 FriendWithEvents txtData As TextBox 16 17 ' labels 18 FriendWithEvents lblEnter As Label 19 FriendWithEvents lblResult As Label 20 21 ' Visual Studio .NET generated code 22 23 Dim array1 As Integer() = NewInteger(19) {} 24 25 ' creates random data 26 PrivateSub cmdCreate_Click(ByVal sender As System.Object, _ 27 ByVal e As System.EventArgs) Handles cmdCreate.Click 28 29 Dim output AsString 30 Dim randomNumber As Random = New Random() 31 Dim i AsInteger 32 33 output = "Index" & vbTab & "Value" & vbCrLf 34 LinearSearchTest.vb
35 ' creates string containing 11 random numbers 36 For i = 0To array1.GetUpperBound(0) 37 array1(i) = randomNumber.Next(1000) 38 output &= i & vbTab & array1(i) & vbCrLf 39 Next 40 41 txtData.Text = output ' displays numbers 42 txtInput.Text = "" ' clear search key text box 43 cmdSearch.Enabled = True' enable search button 44 EndSub' cmdCreate_Click 45 46 ' searches key of element 47 PrivateSub cmdSearch_Click(ByVal sender As System.Object, _ 48 ByVal e As System.EventArgs) Handles cmdSearch.Click 49 50 ' if search key text box is empty, display 51 ' message and exit procedure 52 If txtInput.Text = "" Then 53 MessageBox.Show("You must enter a search key.") 54 Exit Sub 55 EndIf 56 57 Dim searchKey AsInteger = Convert.ToInt32(txtInput.Text) 58 Dim element AsInteger = LinearSearch(searchKey, array1) 59 60 If element <> -1Then 61 lblResult.Text = "Found Value in index " & element 62 Else 63 lblResult.Text = "Value Not Found" 64 EndIf 65 66 EndSub' cmdSearch_Click 67 68 EndClass' FrmLinearSearch LinearSearchTest.vb
1 ' Fig. 7.14: BinarySearchTest.vb 2 ' Demonstrating binary search of an array. 3 4 Imports System.Windows.Forms 5 6 PublicClass FrmBinarySearch 7 Inherits System.Windows.Forms.Form 8 9 ' labels 10 FriendWithEvents lblEnterKey As Label 11 FriendWithEvents lblResult As Label 12 FriendWithEvents lblResultOutput As Label 13 FriendWithEvents lblDisplay As Label 14 FriendWithEvents lblIndex As Label 15 FriendWithEvents lblIndexes As Label 16 17 ' button 18 FriendWithEvents cmdFindKey As Button 19 20 ' text box 21 FriendWithEvents txtInput As TextBox 22 23 ' Visual Studio .NET generated code 24 25 Dim array1 AsInteger() = New Integer(14) {} 26 27 ' FrmBinarySearch initializes array1 to ascending values 28 ' 0, 2, 4, 6, ..., 28 when first loaded 29 PrivateSub FrmBinarySearch_Load(ByVal sender As System.Object, _ 30 ByVal e As System.EventArgs) Handles MyBase.Load 31 32 Dim i AsInteger 33 BinarySearchTest.vb
Receives two arguments, the array to search, and the search key 34 For i = 0To array1.GetUpperBound(0) 35 array1(i) = 2 * i 36 Next 37 38 End Sub ' FrmBinarySearch_Load 39 40 ' event handler for cmdFindKey button 41 PrivateSub cmdFindKey_Click(ByVal sender As System.Object, _ 42 ByVal e As System.EventArgs) Handles cmdFindKey.Click 43 44 Dim searchKey AsInteger = Convert.ToInt32(txtInput.Text) 45 46 lblDisplay.Text = "" 47 48 ' perform binary search 49 Dim element AsInteger = BinarySearch(array1, searchKey) 50 51 If element <> -1Then 52 lblResultOutput.Text = "Found value in element " & element 53 Else 54 lblResultOutput.Text = "Value not found" 55 End If 56 57 End Sub ' cmdFindKey_Click 58 59 ' performs binary search 60Function BinarySearch(ByVal array AsInteger(), _ 61 ByVal key AsInteger) AsInteger 62 63 Dim low AsInteger = 0' low index 64 Dim high AsInteger = array.GetUpperBound(0) ' high index 65 Dim middle AsInteger' middle index 66 BinarySearchTest.vb
Calculates the middle element of the array If 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 67 While low <= high 68 middle = (low + high) \ 2 69 70 ' the following line displays part 71 ' of the array being manipulated during 72 ' each iteration of loop 73 BuildOutput(low, middle, high) 74 75If key = array(middle) Then ' match 76 Return middle 77ElseIf key < array(middle) Then' search low end 78 high = middle - 1' of array 79Else 80 low = middle + 1 81 End If 82 83 End While 84 85 Return-1' search key not found 86 End Function ' BinarySearch 87 88 Sub BuildOutput(ByVal low AsInteger, _ 89 ByVal middle AsInteger, ByVal high AsInteger) 90 91 Dim i AsInteger 92 BinarySearchTest.vb
93 For i = 0 To array1.GetUpperBound(0) 94 95 If i < low OrElse i > high Then 96 lblDisplay.Text &= " " 97 ElseIf i = middle Then ' mark middle element in output 98 lblDisplay.Text &= String.Format("{0:D2}", _ 99 array1(i)) & "* " 100 Else 101 lblDisplay.Text &= String.Format("{0:D2}", _ 102 array1(i)) & " " 103 End If 104 105 Next i 106 107 lblDisplay.Text &= vbCrLf 108 End Sub ' BuildOutput 109 110 EndClass' FrmBinarySearch BinarySearchTest.vb
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
7.9 Multidimensional Rectangular and Jagged Arrays Column 0 Column 1 Column 2 Column 3 a(0, 0) a(0, 1) a(0, 2) a(0, 3) Row 0 Row 1 a(1, 0) a(1, 1) a(1, 2) a(1, 3) a(2, 0) a(2, 1) a(2, 2) a(2, 3) Row 2 Column index Row index (or subscript) Array name Fig. 7.15 Two-dimensional array with three rows and four columns.
Allocates array1 with six initializers in two sublists The declaration and allocation of array2 creates a jagged array of 3 arrays Traverses the array in two dimensions 1 ' Fig. 7.16: MultidimensionalArrays.vb 2 ' Initializing multi-dimensional arrays. 3 4 Imports System.Windows.Forms 5 6 Module modMultidimensionalArrays 7 8 Sub Main() 9 Dim output AsString 10 Dim i, j AsInteger 11 12 ' create rectangular two-dimensional array 13 Dim array1 AsInteger(,) 14 array1 = New Integer(,) {{1, 2, 3}, {4, 5, 6}} 15 16 ' create jagged two-dimensional array 17Dim array2 AsInteger()()= New Integer(2)() {} 18 19 array2(0) = NewInteger() {1, 2} 20 array2(1) = NewInteger() {3} 21 array2(2) = NewInteger() {4, 5, 6} 22 23 output = "Values in array1 by row are " & vbCrLf 24 25For i = 0To array1.GetUpperBound(0) 26 27 For j = 0To array1.GetUpperBound(1) 28 output &= array1(i, j) & " " 29 Next 30 31 output &= vbCrLf 32 Next 33 MultidimensionalArrays.vb
In a jagged two-dimensional array, the second dimension is actually the first dimension of a separate array 34 output &= vbCrLf & "Values in array2 by row are " & _ 35 vbCrLf 36 37 For i = 0To array2.GetUpperBound(0) 38 39For j = 0To array2(i).GetUpperBound(0) 40 output &= array2(i)(j) & " " 41 Next 42 43 output &= vbCrLf 44 Next 45 46 MessageBox.Show(output, _ 47 "Initializing Multi-Dimensional Arrays", _ 48 MessageBoxButtons.OK, MessageBoxIcon.Information) 49 End Sub ' Main 50 51 End Module ' modMultidimensionalArrays MultidimensionalArrays.vb
1 ' Fig 7.17: JaggedArray.vb 2 ' Jagged two-dimensional array example. 3 4 Imports System.Windows.Forms 5 6 Module modJaggedArray 7 Dim lastStudent, lastExam As Integer 8 Dim output As String 9 10 Sub Main() 11 Dim i As Integer 12 13 ' jagged array with 3 rows of exam scores 14 Dim gradeArray AsInteger()() = NewInteger(2)() {} 15 16 ' allocate each row with 4 student grades 17 gradeArray(0) = NewInteger() {77, 68, 86, 73} 18 gradeArray(1) = NewInteger() {98, 87, 89, 81} 19 gradeArray(2) = NewInteger() {70, 90, 86, 81} 20 21 ' upper bounds for array manipulations 22 lastStudent = gradeArray.GetUpperBound(0) 23 lastExam = gradeArray(0).GetUpperBound(0) 24 25 output = "Students \ Exams" & vbCrLf 26 27 ' build output string 28 BuildString(gradeArray) 29 output &= vbCrLf & vbCrLf & "Lowest grade: " & _ 30 Minimum(gradeArray) & vbCrLf & "Highest grade: " & _ 31 Maximum(gradeArray) & vbCrLf 32 JaggedArray.vb
Determines the lowest grade of any student for the semester 33 ' calculate each student's average 34 For i = 0To lastStudent 35 output &= vbCrLf & "Average for student " & _ 36 i & " is " & Average(gradeArray(i)) 37 Next 38 39 MessageBox.Show(output, "Jagged two-dimensional array", _ 40 MessageBoxButtons.OK, MessageBoxIcon.Information) 41 EndSub' Main 42 43 ' find minimum grade 44Function Minimum(ByVal grades AsInteger()()) _ 45 AsInteger 46 47 Dim lowGrade AsInteger = 100 48 Dim i, j AsInteger 49 50 For i = 0To lastStudent 51 52 For j = 0To lastExam 53 54 If grades(i)(j) < lowGrade Then 55 lowGrade = grades(i)(j) 56 EndIf 57 58 Next 59 60 Next 61 62 Return lowGrade 63 End Function' Minimum 64 JaggedArray.vb
Determines the highest grade of any student for the semester Determines a particular student’s semester average 65 ' find the maximum grade 66Function Maximum(ByVal grades As Integer()()) _ 67 As Integer 68 69 Dim highGrade AsInteger = 0 70 Dim i, j AsInteger 71 72 For i = 0To lastStudent 73 74 For j = 0To lastExam 75 76 If grades(i)(j) > highGrade Then 77 highGrade = grades(i)(j) 78 EndIf 79 80 Next 81 82 Next 83 84 Return highGrade 85 End Function' Maximum 86 87 ' determine the average grade for student 88 ' (or set of grades) 89Function Average(ByVal setOfGrades As Integer()) _ 90 As Double 91 92 Dim i As Integer, total As Integer = 0 93 94 ' find sum of student's grades 95 For i = 0To lastExam 96 total += setOfGrades(i) 97 Next 98 99 Return total / setOfGrades.Length 100 End Function ' Average JaggedArray.vb
Appends the two dimensional array to string output in tabular format 101 102 ' creates String displaying array 103Sub BuildString(ByVal grades As Integer()()) 104 Dim i, j As Integer 105 106 ' align column heads 107 output &= " " 108 109 For i = 0To lastExam 110 output &= "(" & i & ") " 111 Next 112 113 For i = 0To lastStudent 114 output &= vbCrLf & "(" & i & ") " 115 116 For j = 0To lastExam 117 output &= grades(i)(j) & " " 118 Next 119 120 Next 121 122 End Sub ' BuildString 123 124 End Module' modJaggedArray JaggedArray.vb
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