Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: " 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."— Presentation transcript:

1  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 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

2  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

3  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

4  2002 Prentice Hall. All rights reserved. 4 7.2 Arrays Fig. 7.1Array consisting of 12 elements. -45 numberArray(0) 6 numberArray(1) 0 numberArray(2) 72 numberArray(3) 1543 numberArray(4) -89 numberArray(5) 0 numberArray(6) 62 numberArray(7) -3 numberArray(8) 1 numberArray(9) 6453 numberArray(10) 78 numberArray(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

5  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

6  2002 Prentice Hall. All rights reserved. 6 7.4 Examples Using Arrays Several examples that demonstrate –Declaration –Allocation –Initialization of arrays

7  2002 Prentice Hall. All rights reserved. Outline 7 CreateArray.vb 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 12 Dim array As 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 18 For i = 0 To 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 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

8  2002 Prentice Hall. All rights reserved. Outline 8 CreateArray.vb 7.4 Examples Using Arrays

9  2002 Prentice Hall. All rights reserved. Outline 9 InitArray.vb 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 12 Dim array1, array2 As Integer() ' declare two arrays 13 14 ' initializer list specifies number of elements 15 ' and value of each element 16 array1 = New Integer() {32, 27, 64, 18, 95, _ 17 14, 90, 70, 60, 37} 18 19 ' allocate array2 based on length of array1 20 array2 = New Integer(array1.GetUpperBound(0)) {} 21 22 ' set values in array2 by a calculation 23 For i = 0 To 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 31 For i = 0 To array1.GetUpperBound(0) 32 output &= i & vbTab & array1(i) & vbTab & array2(i) & _ 33 vbCrLf 34 Next 35 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

10  2002 Prentice Hall. All rights reserved. Outline 10 InitArray.vb 36 MessageBox.Show(output, "Array of Integer Values", _ 37 MessageBoxButtons.OK, MessageBoxIcon.Information) 38 End Sub ' Main 39 40 End Module ' modInitArray

11  2002 Prentice Hall. All rights reserved. Outline 11 SumArray.vb 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 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 = 0 13 14 ' sum array element values 15 For i = 0 To 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 End Sub ' Main 23 24 End Module ' modSumArray Declares, allocates and initializes the 10-element array, array Performs the addition

12  2002 Prentice Hall. All rights reserved. Outline 12 StudentPoll.vb 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 As Integer 10 Dim output As String 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 22 For answer = 0 To responses.GetUpperBound(0) 23 frequency(responses(answer)) += 1 24 Next 25 26 output &= "Rating " & vbTab & "Frequency " & vbCrLf 27 28 For rating = 1 To frequency.GetUpperBound(0) 29 output &= rating & vbTab & frequency(rating) & vbCrLf 30 Next 31 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

13  2002 Prentice Hall. All rights reserved. Outline 13 StudentPoll.vb 32 MessageBox.Show(output, "Student Poll Program", _ 33 MessageBoxButtons.OK, MessageBoxIcon.Information) 34 End Sub ' Main 35 36 End Module ' modStudentPoll

14  2002 Prentice Hall. All rights reserved. Outline 14 Histogram.vb 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 As String ' output string 10 Dim i, j As Integer ' counters 11 12 ' create data array 13 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) & vbTab 21 22 For j = 1 To 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 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

15  2002 Prentice Hall. All rights reserved. Outline 15 Histogram.vb

16  2002 Prentice Hall. All rights reserved. Outline 16 RollDie.vb 1 ' Fig. 7.7: RollDie.vb 2 ' Rolling 12 dice with frequency chart. 3 4 ' Note: Directory.GetCurrentDirectory returns the directory of 5 ' the folder where the current project is plus 6 ' "bin/". This is where the images must be placed 7 ' for the example to work properly. 8 9 Imports System.IO 10 Imports System.Windows.Forms 11 12 Public Class FrmRollDie 13 Inherits System.Windows.Forms.Form 14 15 Dim randomNumber As Random = New Random() 16 Dim frequency As Integer() = New Integer(6) {} 17 18 ' labels 19 Friend WithEvents lblDie1 As Label 20 Friend WithEvents lblDie2 As Label 21 Friend WithEvents lblDie3 As Label 22 Friend WithEvents lblDie4 As Label 23 Friend WithEvents lblDie5 As Label 24 Friend WithEvents lblDie6 As Label 25 Friend WithEvents lblDie7 As Label 26 Friend WithEvents lblDie8 As Label 27 Friend WithEvents lblDie9 As Label 28 Friend WithEvents lblDie11 As Label 29 Friend WithEvents lblDie10 As Label 30 Friend WithEvents lblDie12 As Label 31 32 ' text box 33 Friend WithEvents txtDisplay As TextBox 34

17  2002 Prentice Hall. All rights reserved. Outline 17 RollDie.vb 35 ' button 36 Friend WithEvents cmdRoll As Button 37 38 ' Visual Studio.NET generated code 39 40 ' event handler for cmdRoll button 41 Private Sub cmdRoll_Click(ByVal sender As System.Object, _ 42 ByVal e As System.EventArgs) Handles cmdRoll.Click 43 44 ' pass labels to a method that 45 ' randomly assigns a face to each die 46 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 = 0 60 Dim i As Integer 61 62 For i = 1 To frequency.GetUpperBound(0) 63 total += frequency(i) 64 Next 65 66 txtDisplay.Text = "Face" & vbTab & vbTab & "Frequency" & _ 67 vbTab & vbTab & "Percent" & vbCrLf 68

18  2002 Prentice Hall. All rights reserved. Outline 18 RollDie.vb 69 ' output frequency values 70 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) & "%" & vbCrLf 74 Next 75 76 End Sub ' cmdRoll_Click 77 78 ' simulate roll, display proper 79 ' image and increment frequency 80 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) += 1 88 End Sub ' DisplayDie 89 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

19  2002 Prentice Hall. All rights reserved. Outline 19 RollDie.vb

20  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

21  2002 Prentice Hall. All rights reserved. Outline 21 PassArray.vb 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 As Integer() = New Integer() {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 18 For i = 0 To 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 28 For i = 0 To array1.GetUpperBound(0) 29 output &= " " & array1(i) 30 Next 31 Appends the five elements of array1 to String output Passes array1 to procedure ModifyArray Appends the elements of array1 to output

22  2002 Prentice Hall. All rights reserved. Outline 22 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 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 End Sub ' Main 56 57 ' procedure modifies array it receives (note ByVal) 58 Sub ModifyArray(ByVal arrayParameter As Integer()) 59 Dim j As Integer 60 61 For j = 0 To arrayParameter.GetUpperBound(0) 62 arrayParameter(j) *= 2 63 Next 64 65 End Sub ' ModifyArray 66 Multiplies the elements of arrayParameter by 2

23  2002 Prentice Hall. All rights reserved. Outline 23 PassArray.vb 67 ' procedure modifies integer passed to it 68 ' original is not be modified (note ByVal) 69 Sub ModifyElementByVal(ByVal element As Integer) 70 71 output &= vbCrLf & "Value received in " & _ 72 "ModifyElementByVal: " & element 73 element *= 2 74 output &= vbCrLf & "Value calculated in " & _ 75 "ModifyElementByVal: " & element 76 End Sub ' ModifyElementByVal 77 78 ' procedure modifies integer passed to it 79 ' original is be modified (note ByRef) 80 Sub ModifyElementByRef(ByRef element As Integer) 81 82 output &= vbCrLf & "Value received in " & _ 83 "ModifyElementByRef: " & element 84 element *= 2 85 output &= vbCrLf & "Value calculated in " & _ 86 "ModifyElementByRef: " & element 87 End Sub ' ModifyElementByRef 88 89 End Module ' modPassArray

24  2002 Prentice Hall. All rights reserved. Outline 24 PassArray.vb

25  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

26  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

27  2002 Prentice Hall. All rights reserved. Outline 27 ArrayReferenceTe st.vb 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 24 For i = 0 To 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 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

28  2002 Prentice Hall. All rights reserved. Outline 28 ArrayReferenceTe st.vb 34 ' print contents of firstArray 35 For i = 0 To firstArray.GetUpperBound(0) 36 Console.Write(firstArray(i) & " ") 37 Next 38 39 ' test whether reference was changed by FirstDouble 40 If 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 As Integer() 50 Dim secondArrayCopy As Integer() 51 52 ' allocate secondArray and copy its reference 53 secondArray = New Integer() {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 = 0 To secondArray.GetUpperBound(0) 63 Console.Write(secondArray(i) & " ") 64 Next 65 66 ' pass secondArray using ByRef 67 SecondDouble(secondArray) 68 Compares references firstArray and firstArrayCopy

29  2002 Prentice Hall. All rights reserved. Outline 29 ArrayReferenceTe st.vb 69 Console.Write(vbCrLf & "Contents of secondArray " & _ 70 "after calling SecondDouble: ") 71 72 ' print contents of secondArray after procedure call 73 For i = 0 To 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 End If 85 86 End Sub ' Main 87 88 ' procedure modifies elements of array and assigns 89 ' new reference (note ByVal) 90 Sub FirstDouble(ByVal array As Integer()) 91 Dim i As Integer 92 93 ' double each element value 94 For i = 0 To array.GetUpperBound(0) 95 array(i) *= 2 96 Next 97 98 ' create new reference and assign it to array 99 array = New Integer() {11, 12, 13} 100 End Sub ' FirstDouble 101 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

30  2002 Prentice Hall. All rights reserved. Outline 30 ArrayReferenceTe st.vb 102 ' procedure modifies elements of array and assigns 103 ' new reference (note ByRef) 104 Sub SecondDouble(ByRef array As Integer()) 105 Dim i As Integer 106 107 ' double contents of array 108 For i = 0 To array.GetUpperBound(0) 109 array(i) *= 2 110 Next 111 112 ' create new reference and assign it to array 113 array = New Integer() {11, 12, 13} 114 End Sub ' SecondDouble 115 116 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. 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

31  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

32  2002 Prentice Hall. All rights reserved. Outline 32 BubbleSort.vb 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 7 Sub BubbleSort(ByVal sortArray As Integer()) 8 Dim pass, i As Integer 9 10 For pass = 1 To sortArray.GetUpperBound(0) 11 12 For i = 0 To 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 End Sub ' BubbleSort 23 24 ' swap two array elements 25 Sub Swap(ByVal swapArray As Integer(), _ 26 ByVal first As Integer) 27 28 Dim hold As Integer 29 30 hold = swapArray(first) 31 swapArray(first) = swapArray(first + 1) 32 swapArray(first + 1) = hold 33 End Sub ' Swap 34 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

33  2002 Prentice Hall. All rights reserved. Outline 33 BubbleSortTest.v b 1 ' Fig. 7.11: BubbleSortTest.vb 2 ' Program creates random numbers and sorts them. 3 4 Imports System.Windows.Forms 5 6 Public Class FrmBubbleSort 7 Inherits System.Windows.Forms.Form 8 9 ' buttons 10 Friend WithEvents cmdCreate As Button 11 Friend WithEvents cmdSort As Button 12 13 ' labels 14 Friend WithEvents lblOriginal As Label 15 Friend WithEvents lblSorted As Label 16 17 ' textboxes 18 Friend WithEvents txtOriginal As TextBox 19 Friend WithEvents 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 As Integer 32 33 txtSorted.Text = "" 34

34  2002 Prentice Hall. All rights reserved. Outline 34 BubbleSortTest.v b 35 ' create 10 random numbers and append to output 36 For i = 0 To 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 End Sub ' 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 End Sub ' cmdSort_Click 63 64 End Class ' FrmBubbleSort

35  2002 Prentice Hall. All rights reserved. Outline 35 BubbleSortTest.v b

36  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

37  2002 Prentice Hall. All rights reserved. Outline 37 LinearSearch.vb 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 As Integer, _ 8 ByVal numbers As Integer()) As Integer 9 10 Dim n As Integer 11 12 ' structure iterates linearly through array 13 For n = 0 To numbers.GetUpperBound(0) 14 15 If numbers(n) = key Then 16 17 Return n 18 End If 19 20 Next 21 22 Return -1 23 End Function ' LinearSearch 24 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

38  2002 Prentice Hall. All rights reserved. Outline 38 LinearSearchTest.vb 1 ' Fig. 7.13: LinearSearchTest.vb 2 ' Linear search of an array. 3 4 Imports System.Windows.Forms 5 6 Public Class FrmLinearSearchTest 7 Inherits System.Windows.Forms.Form 8 9 ' buttons 10 Friend WithEvents cmdSearch As Button 11 Friend WithEvents cmdCreate As Button 12 13 ' text boxes 14 Friend WithEvents txtInput As TextBox 15 Friend WithEvents txtData As TextBox 16 17 ' labels 18 Friend WithEvents lblEnter As Label 19 Friend WithEvents lblResult As Label 20 21 ' Visual Studio.NET generated code 22 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.Click 28 29 Dim output As String 30 Dim randomNumber As Random = New Random() 31 Dim i As Integer 32 33 output = "Index" & vbTab & "Value" & vbCrLf 34

39  2002 Prentice Hall. All rights reserved. Outline 39 LinearSearchTest.vb 35 ' creates string containing 11 random numbers 36 For i = 0 To 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 End Sub ' cmdCreate_Click 45 46 ' searches key of element 47 Private Sub 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 End If 56 57 Dim searchKey As Integer = Convert.ToInt32(txtInput.Text) 58 Dim element As Integer = LinearSearch(searchKey, array1) 59 60 If element <> -1 Then 61 lblResult.Text = "Found Value in index " & element 62 Else 63 lblResult.Text = "Value Not Found" 64 End If 65 66 End Sub ' cmdSearch_Click 67 68 End Class ' FrmLinearSearch

40  2002 Prentice Hall. All rights reserved. Outline 40 LinearSearchTest.vb

41  2002 Prentice Hall. All rights reserved. Outline 41 BinarySearchTest.vb 1 ' Fig. 7.14: BinarySearchTest.vb 2 ' Demonstrating binary search of an array. 3 4 Imports System.Windows.Forms 5 6 Public Class FrmBinarySearch 7 Inherits System.Windows.Forms.Form 8 9 ' labels 10 Friend WithEvents lblEnterKey As Label 11 Friend WithEvents lblResult As Label 12 Friend WithEvents lblResultOutput As Label 13 Friend WithEvents lblDisplay As Label 14 Friend WithEvents lblIndex As Label 15 Friend WithEvents lblIndexes As Label 16 17 ' button 18 Friend WithEvents cmdFindKey As Button 19 20 ' text box 21 Friend WithEvents txtInput As TextBox 22 23 ' Visual Studio.NET generated code 24 25 Dim array1 As Integer() = New Integer(14) {} 26 27 ' FrmBinarySearch initializes array1 to ascending values 28 ' 0, 2, 4, 6,..., 28 when first loaded 29 Private Sub FrmBinarySearch_Load(ByVal sender As System.Object, _ 30 ByVal e As System.EventArgs) Handles MyBase.Load 31 32 Dim i As Integer 33

42  2002 Prentice Hall. All rights reserved. Outline 42 BinarySearchTest.vb 34 For i = 0 To array1.GetUpperBound(0) 35 array1(i) = 2 * i 36 Next 37 38 End Sub ' FrmBinarySearch_Load 39 40 ' event handler for cmdFindKey button 41 Private Sub cmdFindKey_Click(ByVal sender As System.Object, _ 42 ByVal e As System.EventArgs) Handles cmdFindKey.Click 43 44 Dim searchKey As Integer = Convert.ToInt32(txtInput.Text) 45 46 lblDisplay.Text = "" 47 48 ' perform binary search 49 Dim element As Integer = BinarySearch(array1, searchKey) 50 51 If element <> -1 Then 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 60 Function BinarySearch(ByVal array As Integer(), _ 61 ByVal key As Integer) As Integer 62 63 Dim low As Integer = 0 ' low index 64 Dim high As Integer = array.GetUpperBound(0) ' high index 65 Dim middle As Integer ' middle index 66 Receives two arguments, the array to search, and the search key

43  2002 Prentice Hall. All rights reserved. Outline 43 BinarySearchTest.vb 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 75 If key = array(middle) Then ' match 76 Return middle 77 ElseIf key < array(middle) Then ' search low end 78 high = middle - 1 ' of array 79 Else 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 As Integer, _ 89 ByVal middle As Integer, ByVal high As Integer) 90 91 Dim i As Integer 92 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

44  2002 Prentice Hall. All rights reserved. Outline 44 BinarySearchTest.vb 93 For i = 0 To array1.GetUpperBound(0) 94 95 If 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 End Class ' FrmBinarySearch

45  2002 Prentice Hall. All rights reserved. Outline 45 BinarySearchTest.vb

46  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

47  2002 Prentice Hall. All rights reserved. 47 7.9 Multidimensional Rectangular and Jagged Arrays Fig. 7.15Two-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 0Column 1Column 2Column 3 Row 0 Row 1 Row 2 Column index Row index (or subscript) Array name

48  2002 Prentice Hall. All rights reserved. Outline 48 Multidimensional Arrays.vb 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 As String 10 Dim i, j As Integer 11 12 ' create rectangular two-dimensional array 13 Dim array1 As Integer(,) 14 array1 = New Integer(,) {{1, 2, 3}, {4, 5, 6}} 15 16 ' create jagged two-dimensional array 17 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 " & vbCrLf 24 25 For i = 0 To array1.GetUpperBound(0) 26 27 For j = 0 To array1.GetUpperBound(1) 28 output &= array1(i, j) & " " 29 Next 30 31 output &= vbCrLf 32 Next 33 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

49  2002 Prentice Hall. All rights reserved. Outline 49 Multidimensional Arrays.vb 34 output &= vbCrLf & "Values in array2 by row are " & _ 35 vbCrLf 36 37 For i = 0 To array2.GetUpperBound(0) 38 39 For j = 0 To 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 In a jagged two-dimensional array, the second dimension is actually the first dimension of a separate array

50  2002 Prentice Hall. All rights reserved. Outline 50 JaggedArray.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 As Integer()() = New Integer(2)() {} 15 16 ' allocate each row with 4 student grades 17 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 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

51  2002 Prentice Hall. All rights reserved. Outline 51 JaggedArray.vb 33 ' calculate each student's average 34 For i = 0 To 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 End Sub ' Main 42 43 ' find minimum grade 44 Function Minimum(ByVal grades As Integer()()) _ 45 As Integer 46 47 Dim lowGrade As Integer = 100 48 Dim i, j As Integer 49 50 For i = 0 To lastStudent 51 52 For j = 0 To lastExam 53 54 If grades(i)(j) < lowGrade Then 55 lowGrade = grades(i)(j) 56 End If 57 58 Next 59 60 Next 61 62 Return lowGrade 63 End Function ' Minimum 64 Determines the lowest grade of any student for the semester

52  2002 Prentice Hall. All rights reserved. Outline 52 JaggedArray.vb 65 ' find the maximum grade 66 Function Maximum(ByVal grades As Integer()()) _ 67 As Integer 68 69 Dim highGrade As Integer = 0 70 Dim i, j As Integer 71 72 For i = 0 To lastStudent 73 74 For j = 0 To lastExam 75 76 If grades(i)(j) > highGrade Then 77 highGrade = grades(i)(j) 78 End If 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) 89 Function 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 = 0 To lastExam 96 total += setOfGrades(i) 97 Next 98 99 Return total / setOfGrades.Length 100 End Function ' Average Determines the highest grade of any student for the semester Determines a particular student’s semester average

53  2002 Prentice Hall. All rights reserved. Outline 53 JaggedArray.vb 101 102 ' creates String displaying array 103 Sub BuildString(ByVal grades As Integer()()) 104 Dim i, j As Integer 105 106 ' align column heads 107 output &= " " 108 109 For i = 0 To lastExam 110 output &= "(" & i & ") " 111 Next 112 113 For i = 0 To lastStudent 114 output &= vbCrLf & " (" & i & ") " 115 116 For j = 0 To lastExam 117 output &= grades(i)(j) & " " 118 Next 119 120 Next 121 122 End Sub ' BuildString 123 124 End Module ' modJaggedArray Appends the two dimensional array to string output in tabular format

54  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

55  2002 Prentice Hall. All rights reserved. Outline 55 ParamArrayTest.v b 1 ' Fig. 7.18: ParamArrayTest.vb 2 ' Using ParamArray to create variable-length parameter lists. 3 4 Module modParamArrayTest 5 6 Sub Main() 7 AnyNumberArguments() 8 AnyNumberArguments(2, 3) 9 AnyNumberArguments(7, 8, 9, 10, 11, 12) 10 11 End Sub ' Main 12 13 ' receives any number of arguments in array 14 Sub AnyNumberArguments(ByVal ParamArray array1 _ 15 As Integer()) 16 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 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

56  2002 Prentice Hall. All rights reserved. Outline 56 ParamArrayTest.v b 34 End Sub ' AnyNumberArguments 35 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.

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

58  2002 Prentice Hall. All rights reserved. Outline 58 ForEach.vb 1 ' Fig. 7.19: ForEach.vb 2 ' Program uses For Each/Next to find a minimum grade. 3 4 Module modForEach 5 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 Integer 11 Dim lowGrade As Integer = 100 12 13 For Each grade In gradeArray 14 15 If grade < lowGrade Then 16 lowGrade = grade 17 End If 18 19 Next 20 21 Console.WriteLine("The minimum grade is: {0}", lowGrade) 22 End Sub ' Main 23 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


Download ppt " 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."

Similar presentations


Ads by Google