Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays. Overview Overview of Arrays Creating Arrays Using Arrays.

Similar presentations


Presentation on theme: "Arrays. Overview Overview of Arrays Creating Arrays Using Arrays."— Presentation transcript:

1 Arrays

2 Overview Overview of Arrays Creating Arrays Using Arrays

3 What Is an Array? An array is a sequence of elements  All elements in an array have the same type  They remain the same size once they are created  Individual elements are accessed using integer indexes  The first element in every array is the zeroth element Integer index 0 (zero) Integer index 4 (four)

4 Array Declaration You declare an array variable by specifying:  The element type of the array  The rank of the array  The name of the variable This specifies the rank of the array This specifies the name of the array variable This specifies the element type of the array Dim name as Type() Dim name() as Type Dim name as Type() Dim name() as Type

5 Array Rank Rank is also known as the array dimension The number of indexes associated with each element Rank 1: One-dimensional Single index associates with each Integer element Rank 2: Two-dimensional Two indexes associate with each Integer element Dim row as Integer() Dim grid as Integer(,)

6 Accessing Array Elements Supply an integer index for each rank  Indexes are zero-based 33 22 11 Dim row as Long()... row(3) Dim row as Long()... row(3) Dim grid as Integer(,)... grid(1,2) Dim grid as Integer(,)... grid(1,2)

7 Checking Array Bounds All array access attempts are bounds checked  A bad index throws an IndexOutOfRangeException  Use the Length property and the GetLength method row grid row.GetLength(0)=6 row.Length=6 grid.GetLength(0)=2 grid.GetLength(1)=4 grid.Length=2*4

8 Creating Array Instances Initializing Array Elements Initializing Multidimensional Array Elements Creating a Computed Size Array Copying Array Variables Creating Arrays

9 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

10 Creating Array Instances Declaring an array variable does not create an array!  You must use new to explicitly create the array instance  Array elements have an implicit default value of zero row 0000 grid 000 000 VariableInstance Dim row as Long()=new Long(3){} Or Dim row as Long()=new Long(0 to 3){} Dim row as Long()=new Long(3){} Or Dim row as Long()=new Long(0 to 3){} Dim grid as Integer(,)=new Integer(1,2){}

11 Initializing Array Elements The elements of an array can be explicitly initialized  You can use a convenient shorthand row 0123 Equivalent dim row as Long() = new long(3) {0, 1, 2, 3} dim row as Long() = {0, 1, 2, 3}

12 Initializing Multidimensional Array Elements You can also initialize multidimensional array elements  All elements must be specified grid 543 210 Implicitly a new Integer(2,3) array  Dim grid as Integer(,) = { {5, 4, 3}, {2, 1, 0} } Dim grid as Integer(,) = { {5, 4, 3}, {2, 1, 0} } Dim grid as Integer(,) = { {5, 4, 3}, {2, 1 } } Dim grid as Integer(,) = { {5, 4, 3}, {2, 1 } }

13 Creating a Computed Size Array The array size does not need to be a compile-time constant  Any valid integer expression will work  Accessing elements is equally fast in all cases Array size specified by compile-time integer constant: Array size specified by run-time integer value: Dim row as Long() = new Long(3){} dim s as String= Console.ReadLine() dim size as Integer = Int32.Parse(s) dim row as Long() = new Long(size-1){} dim s as String= Console.ReadLine() dim size as Integer = Int32.Parse(s) dim row as Long() = new Long(size-1){}

14 Copying Array Variables Copying an array variable copies the array variable only  It does not copy the array instance  Two array variables can refer to the same array instance copy row 0000 VariableInstance dim row as Long() = new long(3){} dim copy as Long() = row... row(0)+=1 dim value as Long = copy(0) Console.WriteLine(value) dim row as Long() = new long(3){} dim copy as Long() = row... row(0)+=1 dim value as Long = copy(0) Console.WriteLine(value)

15 7.5 Passing Arrays to Procedures Passing the Array  Specify the name of the array without using parentheses Method( arrayname) Receiving the array  The procedure’s parameter list must specify that an array will be received Sub Method( ByVal arrayname1() As Integer)

16 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

17 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 57 ' procedure modifies array it receives (note ByVal) 58 Sub ModifyArray(ByVal arrayParameter As Integer()) 59 Dim j As Integer 61 For j = 0 To arrayParameter.GetUpperBound(0) 62 arrayParameter(j) *= 2 63 Next 65 End Sub ' ModifyArray Multiplies the elements of arrayParameter by 2

18 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

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

20 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

21 ArrayReferenceTest.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) 31 Console.Write(vbCrLf & "Contents of firstArray after " & _ 32 "calling FirstDouble: ") 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

22 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 48 ' declare array references 49 Dim secondArray As Integer() 50 Dim secondArrayCopy As Integer() 52 ' allocate secondArray and copy its reference 53 secondArray = New Integer() {1, 2, 3} 54 secondArrayCopy = secondArray 56 Console.WriteLine(vbCrLf & "Test passing array " & _ 57 "reference using ByRef.") 58 Console.Write("Contents of secondArray before " & _ 59 "calling SecondDouble: ") 61 ' print contents of secondArray before procedure call 62 For i = 0 To secondArray.GetUpperBound(0) 63 Console.Write(secondArray(i) & " ") 64 Next 66 ' pass secondArray using ByRef 67 SecondDouble(secondArray) 68 Compares references firstArray and firstArrayCopy

23 69 Console.Write(vbCrLf & "Contents of secondArray " & _ 70 "after calling SecondDouble: ") 72 ' print contents of secondArray after procedure call 73 For i = 0 To secondArray.GetUpperBound(0) 74 Console.Write(secondArray(i) & " ") 75 Next 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 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

24 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

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 1 ' Fig. 7.18: ParamArrayTest.vb 2 ' Using ParamArray to create variable-length parameter lists. 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 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

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

28 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

29 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

30 Dynamic Arrays Use ReDim keyword If you want to change its  size in order to add items  Clean up space when you remove items when an array is redimensioned, by default all of the values in the array are cleared. You can solve it by using Preserve Keyword

31 Tutorial In the above Form, the user is invited to enter values into three Textboxes. The first Textbox is for whatever times table he or she wants. The second Textbox asks for the starting value of the times table. The third Textbox is for the end number of the times table. In other words, 1 times 4, 2 times 4, 3 times 4, right up to 12 times 4.

32 Dim numbers() As Integer Dim startAt As Integer Dim endAt As Integer Dim times As Integer Dim StoreAnswer As Integer Dim i As Integer times = Val(TextBox1.Text) startAt = Val(TextBox2.Text) endAt = Val(TextBox3.Text) ReDim numbers(endAt) For i = startAt To endAt StoreAnswer = i * times numbers(i) = StoreAnswer ListBox1.Items.Add(times & " times " & i & " = " & numbers(i)) Next

33 Jagged Arrays Jagged arrays are maintained as arrays of arrays. Unlike rectangular arrays, rows in jagged arrays can be of different lengths. Dim array1 As Integer()() = New Integer(2)(){} array1(0) = New Integer() {1, 2} array1(1) = New Integer() {3} array1(2) = New Integer() {4, 5, 6} Dim array1 As Integer()() = New Integer(2)(){} array1(0) = New Integer() {1, 2} array1(1) = New Integer() {3} array1(2) = New Integer() {4, 5, 6}

34 50 For i = 0 To array1.GetUpperBound(0) 51 52 For j = 0 To array1(i).GetYpperBound(0) 53 array(i)(j)= 9 58 Next 59 60 Next

35 Array Methods Commonly used methods  Sort – sorts the elements in an array of rank 1 Array.Sort(Array name) Array.Reverse(Array name)  Clear – sets a range of elements to zero or null Array.Clear(Array name, Start Index, length)  Clone – creates a copy of the array ArrayCopy = Array1.Clone  IndexOf – returns the index of the first occurrence of a value Array.IndexOf( Array name, Value)


Download ppt "Arrays. Overview Overview of Arrays Creating Arrays Using Arrays."

Similar presentations


Ads by Google