220 likes | 332 Views
Is there a better way?. Arrays 1. Motivation: to deal with large amounts of data. e.g sorting values :. Input: 10, 15, 4, 15, 17, 3, 12, 36, 48, 32, 9, 21 Want the Output: 3, 4, 9, 10, 12, 15, 17, 21, 25, 32, 36, 48. e.g Compute the average of 7 grades:.
E N D
Is there a better way? Arrays1 Motivation: to deal with large amounts of data e.g sorting values: Input: 10, 15, 4, 15, 17, 3, 12, 36, 48, 32, 9, 21 Want the Output: 3, 4, 9, 10, 12, 15, 17, 21, 25, 32, 36, 48 e.g Compute the average of 7 grades: Dim dblTotal, dblG1,dblG2, dblG3 As Double Dim dblG4, dblG5, dblG6, dblG7 As Double 'Initialize the grades … dblTotal = dblG1+dblG2+dblG3+dblG4 + dblG5+dblG6 MessageBox.Show(“Avg” & FormatNumber(dblTotal/7.0))
Arrays2 • List or series of values OF THE SAME TYPE all referenced by the same name • Similar to list of values for list boxes and combo boxes - without the box • Use an array to keep a series of values for later processing such as • Reordering • Calculating • Printing
ArrayTerms • Element • Individual item in the array • Index (or subscript) • Zero based number used to reference the specific elements in the array • Must be an integer • Boundaries • Lower Subscript, 0 by default • Upper Subscript
Janet Baker George Lee Sue Li Samuel Hoosier Sandra Weeks William Macy Andy Harrison Ken Ford Denny Franks Shawn James (0) (1) (2) (3) (4) (5) (6) (7) (8) (9) Simple Array Example strName Array
Defining Arrays • Use Dim statement to declare • Specify the number of elements in the array as the UpperSubscript General form: DimArrayName(UpperSubscript) asDatatype Example: Dim dblGrades(7) as Double • Each element of the array will be assigned a default value • Numeric ==> 0 • String ==> empty string, 0 characters
Defining Arrays - Alternate Form • You cannot declare the Upper Subscript. The number of elements will be determined by your entry. • Optionally, the elements in the array may be assigned values in the Dim statement (initialized at declaration time) General form: DimArrayName() asDatatype = {InitialValueList} Example: Dim dblGrades()as Double={3.4, 4.0,3.8}
NOTE:3 is the upper index Value. 0 is the lower index Value. There are 4 elements Dim Statement for Arrays Examples - Default Values DimstrName(3) asString Results in an array of 4 elements: strName(0), strName(1), strName(2), strName(3) All initialized to an empty string DimdecBalance(99) as Decimal Results in an array of 100 elements: decBalance(0), . . . , decBalance(99) All initialized to an zero
Dim Statement for Arrays Examples - Assigned Values DimstrDept( ) as String = {"ACT", "MKT", "HR"} DimintActCode( ) as Integer = {10, 20, 30, 40}
strName (0) (1) (2) (3) What does VB do with the array? • When the DIM statement for the array is processed VB sets aside room for it in memory. • Ex: DimstrName(3) as String • VB sets aside a memory location for 4 strings
strName(row) (0) (1) (2) (3) Referencing Array Elements • Use the Index(s) of the Element strName(0) : "Sam Smith" strName(1) : "Jill Creech" strName(2) : "Paul Fry" strName(3) : "Rich Wells" Sam Smith Jill Creech Paul Fry Rich Wells
Some Rules ! (1) No Exceptions OK if 0 iVar1+3+iVar2 7 Index rule: dblGrade(i) An array index must evaluate to an Integerbetween the lower and upper bounds of the array. If the index is not an Integer, VB rounds it to an Integer. Example: Dim dblGrade(7) As Double ... dblGrade(intVar1+3+intVar2) = 3.0 Can have complicated expressions: dblGrade( CInt(3.1*2.71828*Math.Sin(2.*3.14)) )
Some Rules ! (2) No Exceptions Element rule: dblGrade(i) An array element can be used wherever a simple variable of the same type can be used Example lblGrade.Text = FormatNumber (dblGrade(i),0) dblGrade(i)=2^2 *4.5
Working with Arrays • Use Loops to reference each element in the array • For / Next • For Each / Next
For Each Loop General Form For EachElementName In ArrayName Statements to execute Next [ElementName]
For Each / Next • VB references EACH element of the array • VB assigns its value to ElementName • The variable used for ElementName must be same datatype as the array elements or an Object datatype • Makes one pass through the loop per element • Use Exit For statement within loop to exit early
Name of the Array For Each / Next Examples ' Assumes array strName previously dimensioned Dim strOneName As String‘same type as the array For Each strOneName In strName Messagebox.Show(strOneName) ' Write one array element Next strOneName ' Assumes array intTotal previously dimensioned Dim intOneTotal As Integer ForEach intOneTotal In intTotal intOneTotal=0 ' reinitialize the array Next intOneTotal
Program Example(1) Goal: • Get the grades of a class • (the class size may vary) • Display the average grade How? • Have an array • Ask for the size of the class: intClass • Dimension the Array to be big enough • Dim dblGrades(intClass-1) as Double • Get the grades (loop) • compute the average (loop)
Program Example(2)-Input Box strSize contains 110 110 strSize contains "" Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a String containing the content of the text box. strSize = InputBox("Enter class Size","Input")
Code for the example(3) Dim strSize AsString Dim intCounter AsInteger Dim intClassSize AsInteger 'ask user size of the class (number of students) Do strSize = InputBox("Please Enter Size", "Input") IfNot IsNumeric(strSize) Then MessageBox.Show("enter a numeric value") EndIf LoopUntil IsNumeric(strSize) intClassSize = CInt(strSize)
'now create the Array.All elements in the array are initialized to zero Dim dblGrades(intClassSize - 1) AsDouble 'Use a loop to get all of the grades Dim dblGrade AsDouble For intCounter = 0 To dblGrades.Length - 1 'ask the user for the grades and place them in the array Try dblGrade = CDbl(InputBox("Enter Grade")) dblGrades(intCounter) = dblGrade Catch MessageBox.Show("enter a numeric grade") 'Decrement to use the same index value at the next iteration intCounter = intCounter - 1 EndTry Next Code for the example (4)
Code for example (5) 'now we have the array all populated with datawe can calculate the average ‘we are going to use a For Each Next Loop Dim dblGrade AsDouble Dim dblTotalSum AsDouble Dim dblAverage AsDouble ForEach dblGrade In dblGrades dblTotalSum = dblTotalSum + dblGrade Next dblGrade dblAverage = CDbl(dblTotalSum / dblGrades.Length) MessageBox.Show("Average: " & _ FormatNumber(dblAverage, 2)) 'If you wanted to use a normal For Next Loop For intCounter = 0 To _ dblGrades.Length - 1 dblTotalSum = _ dblTotalSum + _ dblGrades(intCounter) Next
Pitfalls of Arrays some constant previously defined But can do this on array elements Write your own functions Dim dblArray1(intSIZE) As Double Dim dblArray2(intSIZE) As Double Suppose dblArray1 has been initialized: Cannot do: dblArray2 = dblArray1; Cannot do:If dblArray1 = dblArray2 ...