Arrays 1
description
Transcript of Arrays 1
110 N-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, 21Want 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 DoubleDim dblG4, dblG5, dblG6, dblG7 As Double'Initialize the grades…dblTotal = dblG1+dblG2+dblG3+dblG4 + dblG5+dblG6 MessageBox.Show(“Avg” & FormatNumber(dblTotal/7.0))
Is there a better way?
Arrays 1
110 N-2
Arrays 2• 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
110 N-3
Array Terms• 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
110 N-4
Simple Array ExamplestrName Array
(0)(1)(2)(3)(4)(5)(6)(7)(8)(9)
Janet BakerGeorge LeeSue LiSamuel HoosierSandra WeeksWilliam MacyAndy HarrisonKen FordDenny FranksShawn James
110 N-5
Defining Arrays • Use Dim statement to declare• Specify the number of elements in the array
as the UpperSubscriptGeneral form:Dim ArrayName(UpperSubscript) as DatatypeExample:Dim dblGrades(7) as Double
•Each element of the array will be assigned a default value
–Numeric ==> 0–String ==> empty string, 0 characters
110 N-6
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:Dim ArrayName( ) as Datatype = {InitialValueList}Example:Dim dblGrades() as Double={3.4, 4.0,3.8}
110 N-7
Dim Statement for Arrays Examples - Default Values
Dim strName(3) as StringResults in an array of 4 elements:
strName(0), strName(1), strName(2), strName(3)
All initialized to an empty string
Dim decBalance(99) as DecimalResults in an array of 100 elements:
decBalance(0), . . . , decBalance(99) All initialized to an zero
NOTE:3 is the upper index Value. 0 is the lower index Value. There are 4 elements
110 N-8
Dim Statement for Arrays Examples - Assigned Values
Dim strDept( ) as String = {"ACT", "MKT", "HR"}Dim intActCode( ) as Integer = {10, 20, 30, 40}
110 N-9
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: Dim strName(3) as String– VB sets aside a memory location for 4 strings
strName(0)(1)(2)(3)
110 N-10
Referencing Array Elements
• Use the Index(s) of the Element
strName(row)(0)(1)(2)(3)
Sam SmithJill CreechPaul FryRich Wells
strName(0) : "Sam Smith"strName(1) : "Jill Creech"strName(2) : "Paul Fry"strName(3) : "Rich Wells"
110 N-11
Example:Dim dblGrade(7) As Double...dblGrade(intVar1+3+intVar2) = 3.0
OK if 0 iVar1+3+iVar2 7 Can have complicated expressions:
dblGrade( CInt(3.1*2.71828*Math.Sin(2.*3.14)) )
An array index must evaluate to anInteger between the lower and upper bounds of the array. If the index is not anInteger, VB rounds it to an Integer. No Exceptions
Index rule: dblGrade(i)Some Rules ! (1)
110 N-12
lblGrade.Text = FormatNumber (dblGrade(i),0)
dblGrade(i)=2^2 *4.5
Example
Element rule:
An array element can be used wherever a simple variable of the same type can be used
No Exceptions
Some Rules ! (2)dblGrade(i)
110 N-13
Working with Arrays
• Use Loops to reference each element in the array– For / Next – For Each / Next
110 N-14
For Each Loop General Form
For Each ElementName In ArrayNameStatements to execute
Next [ElementName]
110 N-15
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
110 N-16
For Each / Next Examples
' Assumes array strName previously dimensionedDim strOneName As String ‘same type as the arrayFor Each strOneName In strName
Messagebox.Show(strOneName) ' Write one array elementNext strOneName
' Assumes array intTotal previously dimensioned Dim intOneTotal As IntegerFor Each intOneTotal In intTotal
intOneTotal=0 ' reinitialize the arrayNext intOneTotal
Name of the Array
110 N-17
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
• Get the grades (loop)
• compute the average (loop)
Program Example(1)
• Dimension the Array to be big enough Dim dblGrades(intClass-1) as Double
110 N-18
110
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")
strSize contains 110
strSize contains ""
Program Example(2)-Input Box
110 N-19
Code for the example(3)
Dim strSize As String
Dim intCounter As Integer
Dim intClassSize As Integer
'ask user size of the class (number of students)
Do
strSize = InputBox("Please Enter Size", "Input")
If Not IsNumeric(strSize) Then
MessageBox.Show("enter a numeric value")
End If
Loop Until IsNumeric(strSize)
intClassSize = CInt(strSize)
110 N-20
Code for the example (4) 'now create the Array. All elements in the array are initialized to zero
Dim dblGrades(intClassSize - 1) As Double
'Use a loop to get all of the grades
Dim dblGrade As Double
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
End Try
Next
110 N-21
Code for example (5)'now we have the array all populated with data we can
calculate the average ‘we are going to use a For Each Next Loop Dim dblGrade As Double Dim dblTotalSum As Double Dim dblAverage As Double For Each 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 LoopFor intCounter = 0 To _ dblGrades.Length - 1 dblTotalSum = _ dblTotalSum + _dblGrades(intCounter) Next
110 N-22
Dim dblArray1(intSIZE) As DoubleDim dblArray2(intSIZE) As Double
some constant previously defined
Suppose dblArray1 has been initialized:Cannot do: dblArray2 = dblArray1;
Cannot do: If dblArray1 = dblArray2 ...
But can do this on array elements
Write your own functions
Pitfalls of Arrays