Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


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

1 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

2 7.2 Arrays Array Position number Length property GetUpperBound method
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

3 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) numberArray(3) 72 numberArray(4) 1543 numberArray(5) -89 numberArray(6) numberArray(7) 62 numberArray(8) -3 Position number (index or subscript) of the element within array numberArray numberArray(9) 1 numberArray(10) 6453 numberArray(11) 78 Fig. 7.1 Array consisting of 12 elements.

4 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

5 Several examples that demonstrate
7.4 Examples Using Arrays Several examples that demonstrate Declaration Allocation Initialization of arrays

6 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 Sub Main() Dim output As String Dim i As Integer 11 Dim array As Integer() ' declare array variable array = New Integer(9) {} ' allocate memory for array 14 output &= "Subscript " & vbTab & "Value" & vbCrLf 16 ' display values in array For i = 0 To array.GetUpperBound(0) output &= i & vbTab & array(i) & vbCrLf Next 21 output &= vbCrLf & "The array contains " & _ array.Length & " elements." 24 MessageBox.Show(output, "Array of Integer Values", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main 28 29 End Module ' modCreateArray CreateArray.vb 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

7 7.4 Examples Using Arrays CreateArray.vb

8 One statement is used to declare the two arrays
1 ' Fig. 7.3: InitArray.vb 2 ' Initializing arrays. 3 4 Imports System.Windows.Forms 5 6 Module modInitArray 7 Sub Main() Dim output As String Dim i As Integer 11 Dim array1, array2 As Integer() ' declare two arrays 13 ' initializer list specifies number of elements ' and value of each element array1 = New Integer() {32, 27, 64, 18, 95, _ , 90, 70, 60, 37} 18 ' allocate array2 based on length of array1 array2 = New Integer(array1.GetUpperBound(0)) {} 21 ' set values in array2 by a calculation For i = 0 To array2.GetUpperBound(0) array2(i) = * i Next 26 output &= "Subscript " & vbTab & "Array1" & vbTab & _ "Array2" & vbCrLf 29 ' display values for both arrays For i = 0 To array1.GetUpperBound(0) output &= i & vbTab & array1(i) & vbTab & array2(i) & _ vbCrLf Next 35 InitArray.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

9 InitArray.vb 36 MessageBox.Show(output, "Array of Integer Values", _
MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main 39 40 End Module ' modInitArray InitArray.vb

10 Declares, allocates and initializes the 10-element array, array
1 ' Fig. 7.4: SumArray.vb 2 ' Computing sum of elements in array. 3 4 Imports System.Windows.Forms 5 6 Module modSumArray 7 Sub Main() Dim array As Integer() = New Integer() _ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 11 Dim total As Integer = 0, i As Integer = 0 13 ' sum array element values For i = 0 To array.GetUpperBound(0) total += array(i) Next 18 MessageBox.Show("Total of array elements: " & total, _ "Sum the elements of an Array", MessageBoxButtons.OK, _ MessageBoxIcon.Information) End Sub ' Main 23 24 End Module ' modSumArray Declares, allocates and initializes the 10-element array, array SumArray.vb Performs the addition

11 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

12 Appends the five elements of array1 to String 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 Dim output As String 8 Sub Main() Dim array1 As Integer() = New Integer() {1, 2, 3, 4, 5} Dim i As Integer 12 output = "EFFECTS OF PASSING ENTIRE ARRAY " & _ "BY REFERENCE:" & vbCrLf & vbCrLf & _ "The values of the original array are:" & vbCrLf 16 ' display original elements of array1 For i = 0 To array1.GetUpperBound(0) output &= " " & array1(i) Next 21 ModifyArray(array1) ' array is passed by reference 23 output &= vbCrLf & _ "The values of the modified array are:" & vbCrLf 26 ' display modified elements of array1 For i = 0 To array1.GetUpperBound(0) output &= " " & array1(i) Next 31 PassArray.vb Appends the five elements of array1 to String output Passes array1 to procedure ModifyArray Appends the elements of array1 to output

13 Multiplies the elements of arrayParameter by 2
output &= vbCrLf & vbCrLf & _ "EFFECTS OF PASSING ARRAY ELEMENT " & _ "BY VALUE:" & vbCrLf & vbCrLf & "array1(3) " & _ "before ModifyElementByVal: " & array1(3) 36 ' array element passed by value ModifyElementByVal(array1(3)) 39 output &= vbCrLf & "array1(3) after " & _ "ModifyElementByVal: " & array1(3) 42 output &= vbCrLf & vbCrLf & "EFFECTS OF PASSING " & _ "ARRAY ELEMENT BY REFERENCE: " & vbCrLf & vbCrLf & _ "array1(3) before ModifyElementByRef: " & array1(3) 46 ' array element passed by reference ModifyElementByRef(array1(3)) 49 output &= vbCrLf & "array1(3) after " & _ "ModifyElementByRef: " & array1(3) 52 MessageBox.Show(output, "Passing Arrays", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main 56 ' procedure modifies array it receives (note ByVal) Sub ModifyArray(ByVal arrayParameter As Integer()) Dim j As Integer 60 For j = 0 To arrayParameter.GetUpperBound(0) arrayParameter(j) *= 2 Next 64 End Sub ' ModifyArray 66 PassArray.vb Multiplies the elements of arrayParameter by 2

14 PassArray.vb 67 ' procedure modifies integer passed to it
' original is not be modified (note ByVal) Sub ModifyElementByVal(ByVal element As Integer) 70 output &= vbCrLf & "Value received in " & _ "ModifyElementByVal: " & element element *= 2 output &= vbCrLf & "Value calculated in " & _ "ModifyElementByVal: " & element End Sub ' ModifyElementByVal 77 ' procedure modifies integer passed to it ' original is be modified (note ByRef) Sub ModifyElementByRef(ByRef element As Integer) 81 output &= vbCrLf & "Value received in " & _ "ModifyElementByRef: " & element element *= 2 output &= vbCrLf & "Value calculated in " & _ "ModifyElementByRef: " & element End Sub ' ModifyElementByRef 88 89 End Module ' modPassArray PassArray.vb

15 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

16 7.6 Passing Arrays: ByVal vs. 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

17 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 Sub Main() Dim i As Integer 9 ' declare array references Dim firstArray As Integer() Dim firstArrayCopy As Integer() 13 ' allocate firstArray and copy its reference firstArray = New Integer() {1, 2, 3} firstArrayCopy = firstArray 17 Console.WriteLine("Test passing array reference " & _ "using ByVal.") Console.Write("Contents of firstArray before " & _ "calling FirstDouble: ") 22 ' print contents of firstArray For i = 0 To firstArray.GetUpperBound(0) Console.Write(firstArray(i) & " ") Next 27 ' pass firstArray using ByVal FirstDouble(firstArray) 30 Console.Write(vbCrLf & "Contents of firstArray after " & _ "calling FirstDouble: ") 33 ArrayReferenceTest.vb 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

18 Compares references firstArray and firstArrayCopy
' print contents of firstArray For i = 0 To firstArray.GetUpperBound(0) Console.Write(firstArray(i) & " ") Next 38 ' 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 47 ' declare array references Dim secondArray As Integer() Dim secondArrayCopy As Integer() 51 ' allocate secondArray and copy its reference secondArray = New Integer() {1, 2, 3} secondArrayCopy = secondArray 55 Console.WriteLine(vbCrLf & "Test passing array " & _ "reference using ByRef.") Console.Write("Contents of secondArray before " & _ "calling SecondDouble: ") 60 ' print contents of secondArray before procedure call For i = 0 To secondArray.GetUpperBound(0) Console.Write(secondArray(i) & " ") Next 65 ' pass secondArray using ByRef SecondDouble(secondArray) 68 Compares references firstArray and firstArrayCopy ArrayReferenceTest.vb

19 Bubble Sort (a.k.a. sinking sort)
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

20 7.8 Searching Arrays: Linear Search and Binary Search
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

21 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

22 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 Two-dimensional array with three rows and four columns.

23 Allocates array1 with six initializers in two sublists
1 ' Fig. 7.16: MultidimensionalArrays.vb 2 ' Initializing multi-dimensional arrays. 3 4 Imports System.Windows.Forms 5 6 Module modMultidimensionalArrays 7 Sub Main() Dim output As String Dim i, j As Integer 11 ' create rectangular two-dimensional array Dim array1 As Integer(,) array1 = New Integer(,) {{1, 2, 3}, {4, 5, 6}} 15 ' create jagged two-dimensional array Dim array2 As Integer()() = New Integer(2)() {} 18 array2(0) = New Integer() {1, 2} array2(1) = New Integer() {3} array2(2) = New Integer() {4, 5, 6} 22 output = "Values in array1 by row are " & vbCrLf 24 For i = 0 To array1.GetUpperBound(0) 26 For j = 0 To array1.GetUpperBound(1) output &= array1(i, j) & " " Next 30 output &= vbCrLf Next 33 MultidimensionalArrays.vb 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

24 In a jagged two-dimensional array, the second dimension is actually the first dimension of a separate array output &= vbCrLf & "Values in array2 by row are " & _ vbCrLf 36 For i = 0 To array2.GetUpperBound(0) 38 For j = 0 To array2(i).GetUpperBound(0) output &= array2(i)(j) & " " Next 42 output &= vbCrLf Next 45 MessageBox.Show(output, _ "Initializing Multi-Dimensional Arrays", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main 50 51 End Module ' modMultidimensionalArrays MultidimensionalArrays.vb

25 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

26 Applies keyword ParamArray to array1
1 ' Fig. 7.18: ParamArrayTest.vb 2 ' Using ParamArray to create variable-length parameter lists. 3 4 Module modParamArrayTest 5 Sub Main() AnyNumberArguments() AnyNumberArguments(2, 3) AnyNumberArguments(7, 8, 9, 10, 11, 12) 10 End Sub ' Main 12 ' receives any number of arguments in array Sub AnyNumberArguments(ByVal ParamArray array1 _ As Integer()) 16 Dim i, total As Integer total = 0 19 If array1.Length = 0 Then Console.WriteLine("Procedure AnyNumberArguments" & _ " received 0 arguments.") Else Console.Write("The total of ") 25 For i = 0 To array1.GetUpperBound(0) Console.Write(array1(i) & " ") total += array1(i) Next 30 Console.WriteLine("is {0}.", total) End If 33 Calls procedure AnyNumberArguments, passing a different number of arguments each time ParamArrayTest.vb Applies keyword ParamArray to array1 Determines whether or not zero arguments where passed, if not displays array1’s elements and their sum

27 34 End Sub ' AnyNumberArguments 35 36 End Module ' modParamArrayTest
ParamArrayTest.vb Procedure AnyNumberArguments received 0 arguments. The total of 2 3 is 5. The total of is 57.

28 7.11 For Each/Next Repetition Structure
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

29 1 ' Fig. 7.19: ForEach.vb 2 ' Program uses For Each/Next to find a minimum grade. 3 4 Module modForEach 5 Sub Main() Dim gradeArray As Integer(,) = New Integer(,) _ {{77, 68, 86, 73}, {98, 87, 89, 81}, {70, 90, 86, 81}} 9 Dim grade As Integer Dim lowGrade As Integer = 100 12 For Each grade In gradeArray 14 If grade < lowGrade Then lowGrade = grade End If 18 Next 20 Console.WriteLine("The minimum grade is: {0}", lowGrade) End Sub ' Main 23 24 End Module ' modForEach ForEach.vb 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 The minimum grade is: 68


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

Similar presentations


Ads by Google