Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley More About Array Processing 8.2 There Are Many Uses of Arrays and Many Programming Techniques That Involve Them For Example, Arrays Are Used to Total Values or Search for Data
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 2 Determining Number of Elements Arrays have a Length property that holds the number of elements in the array Note that length is number of array elements, not the upper subscript of the array Length property always 1 greater than the upper subscript Dim values(25) As Integer For count = 0 to (values.Length – 1) MessageBox.Show(values(count).ToString) Next count
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 3 Total the Values in an Array Variable to hold sum ( intTotal) is initialized to zero prior to loop Iterate over all elements, adding each element to intTotal Dim intUnits(24) as Integer‘Declare array Dim intTotal As Integer = 0'Initialize accumulator Dim intCount as Integer‘Declare loop counter ‘Find total of all values held in array For intCount = 0 To (intUnits.Length – 1) intTotal += intUnits(intCount) Next intCount
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 4 Average the Values in an Array Similar to previous example but then divides total by number of elements to get average Dim intUnits(24) as Integer‘Declare array Dim intTotal As Integer = 0'Initialize accumulator Dim dblAverage as Double‘Declare average var Dim intCount as Integer‘Declare loop counter ‘Find total of all values held in array For intCount = 0 To (intUnits.Length – 1) intTotal += intUnits(intCount) Next intCount ‘Use floating-point division to compute average dblAverage = intTotal / intUnits.Length
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 5 Find Highest & Lowest Array Values Pick first element as the highest Search rest of array for higher values If a higher value is located, save the value Use similar logic to find lowest value Dim intNumbers(24) as Integer Dim intCount as Integer Dim intHighest as Integer = intNumbers(0) For intCount = 1 To (intNumbers.Length - 1) If intNumbers(intCount) > intHighest Then intHighest = intNumbers(intCount) End If Next intCount
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 6 Copy Values in One Array to Another Done by copying elements one at a time Note that this cannot be done by a simple assignment newValues = oldValues For intCount = 0 To 100 newValues(intCount) = oldValues(intCount) Next intCount
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 7 Parallel Arrays Sometimes useful to store related data in two or more arrays called parallel arrays Causes the i th element of one array to be related to the i th element of another Allows related data to be accessed using the same subscript on both arrays
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 8 Parallel Arrays Example Assume the following array declarations Element 1 refers to the same person with name in one array and address in the other Dim names(4) As String Dim addresses(4) As String Names(0) Names(1) Names(2) Names(3) Names(4) Addresses(0) Addresses(1) Addresses(2) Addresses(3) Addresses(4) Person #1Person #2Person #3Person #4Person #5
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 8- 9 Parallel Arrays Processing Dim names(4) As String Dim addresses(4) As String For intCount = 0 To 4 lstPeople.Items.Add("Name: " & names(intCount) & _ " Address: " & addresses(intCount)) Next intCount Use parallel array processing to add name and address of each person to a list box Tutorial 8-2 has an example of parallel arrays
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Searching Arrays, The Search Find 1 st instance of value 100 in array scores intPosition gives position of this value Dim blnFound as Boolean = False Dim intCount as Integer = 0 Dim intPosition as Integer = -1 ‘ Search for a 100 in the array Do While Not blnFound And intCount < scores.Length If scores(intCount) = 100 Then blnFound = True intPosition = intCount End If intCount += 1 Loop
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Searching Arrays, The Result Indicates whether the value was found If found, position is given as a test number ' Was 100 found in the array? If blnFound Then MessageBox.Show( _ “There was a 100 on the test " & _ (intPosition + 1).ToString, "Test Results") Else MessageBox.Show( _ “No one got a 100, but keep trying!", _ "Test Results") End If
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Sorting an Array Arrays have a Sort method Arranges elements in ascending order (lowest to highest) Sorted so that numbers = {1, 3, 6, 7, 12} Sorted so that names = {Alan, Bill, Kim, Sue} Dim numbers() As Integer = { 7, 12, 1, 6, 3 } Array.Sort(numbers) Dim names() As String = { "Sue", "Kim", _ "Alan", "Bill" } Array.Sort(names)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Resizing an Array ReDim is a new keyword If Preserve is specified, the existing contents of the array are preserved Arrayname names the existing array UpperSubscript specifies the new highest subscript value Can declare an array with no subscript and state number of elements later with ReDim ReDim [Preserve] Arrayname(UpperSubscript)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Resizing Example Dim scores() As Single' Declared with no elements Dim numScores as Integer ' Obtain number of elements from the user numScores = CInt(InputBox("Enter number of test scores")) If numScores > 0 Then ReDim scores(numScores - 1) Else MessageBox.Show("You must enter 1 or greater.") End If Array scores declared with no elements User prompted for number of elements ReDim resizes array based on user input
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Sub Procedures and Functions That Work With Arrays 8.3 You May Pass Arrays As Arguments to Sub Procedures and Functions You May Also Return an Array From a Function This Allows You to Write Sub Procedures and Functions That Perform General Operations With Arrays
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Passing Arrays as Arguments Dim numbers() As Integer = { 2, 4, 7, 9, 8, 12, 10 } DisplaySum(numbers) Sub DisplaySum(ByVal intArray() As Integer) Dim total As Integer = 0 ' Accumulator Dim count As Integer ' Loop counter For count = 0 To (intArray.Length - 1) total += intArray(count) Next MessageBox.Show(“Total is " & total.ToString) End Sub Array numbers passed to DisplaySum sub Sub computes/shows sum of array elements Can pass any integer array to DisplaySum
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Passing Arrays: ByVal and ByRef When passing an array ByVal Calling procedure “sees” sub procedure changes to element values Simple variables don’t work this way If sub assigns array argument to another array, no effect on array in calling procedure When passing an array ByRef Calling procedure “sees” sub procedure changes to element values If sub assigns array argument to another array, calling procedure array values affected
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Passing Arrays Example Dim numbers() As Integer = { 1, 2, 3, 4, 5 } ResetValues(numbers) Sub ResetValues(ByVal intArray() As Integer) Dim newArray() As Integer = {0, 0, 0, 0, 0} intArray = newArray End Sub After ResetValues procedure executes, numbers array still contains { 1, 2, 3, 4, 5 } If array passed ByRef, numbers array will contain { 0, 0, 0, 0, 0 } after procedure runs
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide An Array Returned From a Function Function GetNames() As String() ' Get four names from user ' Return them as an array of strings. Dim strNames(3) As String Dim strInput As String Dim count As Integer For count = 0 To 3 strInput = InputBox("Enter name " & _ (count + 1).ToString) strNames(count) = strInput Next Return strNames End Function Return type String() indicates an array of strings Thus the function result must be assigned to an array of strings
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Multidimensional Arrays 8.4 You May Create Arrays With More Than Two Subscripts to Hold Complex Sets of Data
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide A Two Dimensional Array Picture Column 0Column 1Column 2Column 3 Row 0 Row 1 Row 2 Thus far, arrays have been one-dimensional However, arrays can also be two-dimensional Picture a two-dimensional array like a spreadsheet with rows and columns
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Two Dimensional Array Syntax UpperRow and UpperColumn give the highest subscript for the row and column indices of the array The array on the previous slide could be: Defines three rows; 0, 1, and 2 And four columns; 0, 1, 2, and 3 Dim ArrayName(UpperRow, UpperColumn) As DataType Dim array(2,3) As Single
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Two Dimensional Array Subscripts Dim array(2,3) As Single Column 0Column 1Column 2Column 3 Row 0array(0,0)array(0,1)array(0,2)array(0,3) Row 1array(1,0)array(1,1)array(1,2)array(1,3) Row 2array(2,0)array(2,1)array(2,2)array(2,3)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Nested Loops And Two Dimensions For row = 0 To 2 For col = 0 To 3 num = Val(InputBox("Enter a score.")) scores(row, col) = num Next col Next row Nested loops are often used in processing two- dimensional arrays In the example, a nested loop is used to insert a value into every element of array scores
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Implicit Sizing and Initialization Can be used with multi-dimensional arrays: Row 0 values Row 1 values Row 2 values Initializes array numbers with the following values Dim numbers(,) As Integer = _ { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } Col 0Col 1Col 2 Row 0123 Row 1456 Row 2789
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide For Each Loop With Two Dimensions A For Each Loop will process all elements of an array without requiring nested loops The example below computes the sum of all elements Total has the value 45 when loop is complete Dim numbers(,) As Integer = {{1, 2, 3}, _ {4, 5, 6}, _ {7, 8, 9}} For Each element In numbers total += element Next element
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Sum Two-Dimensional Array Columns ' Process each column in turn For col = 0 To 2 ' Initialize column accumulator total = 0 ' Sum the column values from each row For row = 0 To 4 total += values(row, col) Next row ' Display the sum of the column. MessageBox.Show("Sum of column " & _ col.ToString & " is " & total.ToString) Next col Outer loop controls column subscript Inner loop controls row subscript
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide Three-Dimensional Arrays & Beyond VB allows arrays of up to 32 dimensions Beyond three dimensions, they are difficult to visualize But, all one needs to do is to be consistent in the use of the different indices