Arrays 1
Arrays 1
04/04/15
Example
Task: Evaluate exam scores for 30 students.
To store 30 names and scores, you could do this:
Dim
Dim
Dim
Dim
student0
grade0 =
student1
grade1 =
...
This results in too much code, and also makes it hard to work with as the amount of data
grows.
04/04/15
Why Arrays?
Why isnt this enough to create an indexed list? Why do we
need an array variable?
For i As Integer = 0 To 29
studenti = InputBox(Enter name of Student & i, Name)
gradei = InputBox(Enter grade of Student & i, Grade)
Next
04/04/15
Indexed Lists
Wouldnt it be great to be able to create an indexed list
instead of creating individual variables?
student(0), student(1), , student(29)
grade(0), grade(1), , grade(29)
Why?
For i As Integer = 0 To 29
student(i) = InputBox(Enter name of Student & i, Name)
grade(i) = InputBox(Enter grade of Student & i, Grade)
Next
Arrays
Arrays are variables that hold multiple values.
indexed list of simple variables of same data type
Array variables have a parameter called a subscript or
index that indicates which element to store/retrieve.
We use array variables, simply known as Array
04/04/15
Array
Index
grade(0) grade(1)
Element
grade(2)
Zero-based indexing
Naming convention for arrays: camel casing
04/04/15
grade(29)
Declaring Arrays
The basic syntax for declaring an array is:
Dim name(upperBound) As DataType
Example: Dim studentNames(29) As String
upperBound controls the size of the array by indicating
the uppermost subscript.
Subscripts are 0-based.
04/04/15
Example w/Arrays
The previous example (60 declarations) can be reduced to 2
declarations!
Dim student(29) As String
Dim grade(29) As Double
The above example declares 2 variables
Each variable holds 30 values (indices 0 29)
The technique of using two or more arrays in conjunction with
each other is called parallel arrays. Why?
04/04/15
Array Vocabulary
The lower bound of an array is 0.
The upper bound is specified by the programmer in the declaration
statement
29 in the previous example.
The size of the array is the upper bound + 1
The previous example arrays hold 30 values each (29 + 1)
Assigning Values
Default Initialization:
String arrays -> null, Integer arrays -> 0, Date arrays -> #1/1/0001#
Dim student(29) As String
Dim grade(29) As Double
Always use a subscript when reading or writing values from/to an
array:
student(0) = Tom Brown
The above statement stores the string Tom Brown in the first cell of
the array.
The index or subscript is usually read as name sub x.
04/04/15
grade(29)=90
Or
For i As Integer = 0 To 29
grade(i)= InputBox(Enter grade of Student & i, Grade)
Next
04/04/15
04/04/15
Scope of Arrays
Similar to variables
If an array variable is declared in the class (e.g., Form)
then it is a class-level array variable
Available to all procedures in the form
Any value assigned to it in a procedure will persist
after the procedure terminates
Array variables declared within a procedure are local to
that procedure and cease to exist as soon as the
procedure is exited
04/04/15
Book Example
mtxtNumber
txtWinner
04/04/15
Book Example
Private Sub btnWhoWon_Click(...) _Handles btnWhoWon.Click
Dim teamName(3) As String
Dim n As Integer
'Place Super Bowl Winners into the array
teamName(0) = "Packers"
teamName(1) = "Packers"
teamName(2) = "Jets"
teamName(3) = "Chiefs
'Access array
n = CInt(txtNumber.Text)
txtWinner.Text = teamName(n - 1)
End Sub
04/04/15
Example Output
04/04/15
Example Notes
The example code is not very efficient.
Every time the user presses the button, the array is declared and
initialized with the first four values.
This declaration and initialization consumes unnecessary processing on
the part of the computer.
It would be better to declare and initialize the array once!
You can do this upon application initialization with the forms Load
event.
04/04/15
Optimized Example
Dim teamName(3) As String
04/04/15
Array Initialization
Similar to scalar variables, arrays may be initialized upon declaration:
Dim arrayName() As varType = {value0, value1, value2, ...,
valueN}
The previous example becomes:
Dim teamName() As String = {Packers, Packers, Jets,
Chiefs}
notice
Recap
Simple variables can be assigned a single value
What to do when we have to work with a list of values (e.g.,
list of student names, US states, etc.)?
We use array variables, simply known as Array
Array variables are an indexed list of variables of the same
data type.
Creating an array:
Ex 1: Dim students(29) As String
Ex 2: Dim students() As String = {Emma, Alice,
Cathy}
Array Assignment
Values known at initialization:
Dim teamName() As String = {Packers, Packers,
Jets, Chiefs}
Values to be inputted later:
Dim teamName(3) As String
Initialized to Null
For i = 0 To 3
teamName(i)=InputBox(Enter team name & i, Name)
Next
04/04/15
Array Methods
Methods for both Numeric and String arrays:
Dim teamNames() As String = {Packers, Packers, Jets,
Chiefs}
Expressions
Values
teamNames.Count
4
teamNames.Max Packers
teamNames.Min Chiefs
teamNames.First
Packers
teamNames.Last
Chiefs
04/04/15
Practice Problems
Exercises 7.1 (Pg. 285-290)
3, 5, 7, 8, 11, 17, 29
04/04/15
ReDim Statement
After an array has been declared, its upper bound (but not its
data type) can be changed
Dim grade(29) As Double
ReDim grade(59)
Note: datatype cant be changed,
hence not mentioned
Or
For i As Integer = 0 To grade.Count-1
lstBox.Items.Add(grade(i))
Next
04/04/15
Functions returning
Arrays
Example:
Private Sub btnGet_Click() Handles btnGet.Click
Dim numGrades As Integer = CInt(InputBox(Number of Grades: ,
Grades))
txtAverage.Text = CStr(GetGrades(numGrades).Average)
End Sub
Function GetGrades(numGrades As Integer) As Double()
Dim grades(numGrades-1) As Double
For i As Integer = 1 To numGrades
grades(i-1)=CDbl(InputBox(Grade # & i & : , Grades))
Next
Return grades
End Function
04/04/15
Searching an Array
Searching for an element in an array
numVar = Array.IndexOf(arrayName, value)
04/04/15
Copying an Array
Declared with same Datatype
arrayTwo = arrayOne
arrayTwo references the same array as arrayOne
Same size, contains same data
Copying an Array
Copying without sharing memory
For i As Integer = 0 To arrayOne.Count 1
arrayTwo(i)=arrayOne(i)
Next
04/04/15
Split Method
Split method provides another way to assign values to
an array
Dim teamNames(3) As String
Dim line As String = Packers,Packers,Jets,Chiefs
teamNames = line.Split(,c)
04/04/15
Join Function
Join is the reverse of split
Returns a string value consisting of the elements of an array
concatenated together and separated by a specified delimiter.
Dim greatLakes() As String = {Huron, Ontario,
Michigan, Erie, Superior}
Dim lakes As String
lakes = Join(greatLakes, ,c}
txtOutput.Text = lakes
Output: Huron,Ontario,Michigan,Erie,Superior
04/04/15
Passing Array to a
Procedure
A local array can be passed to another procedure
Argument in the calling statement consists of the name of
the array
The corresponding parameter in the header of the
procedure must consists of an array name with ()
Private Sub btnCalculate_Click() Handles
Dim ages() As Integer ={55, 56, 61, 52, 47}
txtOutput.Text= The maximum age is & Maximum(ages)
End Sub
04/04/15
Passing Array to a
Procedure (2)
04/04/15
Summary (1)
Declaring and assigning values to arrays:
A. Dim students(1) As String
students(0) = Archie
students(1) = Veronica
Summary (2)
Passing arrays to functions
Private Sub btnGet_Click() Handles btnGet.Click
Dim arr() As Integer = {23, 34, 55, 60, 83}
txtOutput.Text = total(arr)
End Sub
Function total(ByRef arr() As Integer) As Integer
Dim tot As Integer = 0
For Each value As Integer In arr
tot + = value
Next
Return tot
End Function
04/04/15
Summary (3)
Returning arrays from functions
Private Sub btnGet_Click() Handles btnGet.Click
Dim num As Integer = CInt(InputBox(No. of Students: , Scores))
txtMaxScore.Text = CStr(GetScores(num).Max)
End Sub
Function GetScores(num As Integer) As Double()
Dim scores(num-1) As Double
For i As Integer = 0 To (num - 1)
scores(i)=CDbl(InputBox(Score of student & i & : , Scores))
Next
Return scores
End Function
04/04/15
04/04/15
Text Files
To read data from a text file:
1.
Copy the file to the Debug directory containing your executable
2.
Add a line like the following to your program:
Dim strArrayName() As String = IO.File.ReadAllLines(filename)
Where strArrayName is the name of your array (as determined by you), and filename
is the name of your file (usually ends in .txt)
Example:
Dim numStr() As String = IO.File.ReadAllLines("Numbers.txt")
04/04/15