Вы находитесь на странице: 1из 42

Taking a step back

In IDSC 3101 we discussed variables that contain a


single value.
These are formally called scalar variables.
How to store the name and grade of a student?
Dim student As String (e.g., Alice)
Dim grade As Double (e.g., 88.5)

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 As String, score0 As Double


student1 As String, score1 As Double
student2 As String, score2 As Double
student29 As String, score29 As Double

student0
grade0 =
student1
grade1 =
...

= InputBox(Enter name of Student & 0, Name)


InputBox(Enter grade of Student & 0, Grade)
= InputBox(Enter name of Student & 1, Name)
InputBox(Enter grade of Student & 1, Grade)

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

Easy to input, process, output!


04/04/15

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)

Negative subscript or a subscript greater then the upper


bound of an array is not allowed.
04/04/15

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

Assigning Values (2)


Dim grade(29) As Double
grade(0)=92
grade(1)=85

grade(29)=90

Or
For i As Integer = 0 To 29
grade(i)= InputBox(Enter grade of Student & i, Grade)
Next

04/04/15

Outputting Array values


Dim grade(29) As Double
grade(0)=92
grade(1)=85
For i As Integer = 0 To 2
lstBox.Items.Add(grade(i))
Next
What will be the output in the Listbox?

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

Note class-level variable

Private Sub frmBowl_Load(...) Handles MyBase.Load


'Place Super Bowl Winners into the array
teamName(0) = "Packers"
teamName(1) = "Packers"
teamName(2) = "Jets"
teamName(3) = "Chiefs"
End Sub
Private Sub btnWhoWon_Click(...) Handles btnWhoWon.Click
Dim n As Integer
n = CInt(txtNumber.Text)
txtWinner.Text = teamName(n - 1)
End Sub
NOTE: Be very careful when using class-level variables!

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

Note that string variables are placed within


Note that you do not need to specify an upper bound in this case.
Dim grades(3) As Double = {90, 87, 90, 80} is invalid. Why?
04/04/15

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}

Accessing array variables (aka elements of the array):


students(2)=Tom Assigns Tom to array variable at index 2
txtBox.Text = students(2) Displays Tom in the textbox
04/04/15

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

Additionally, for Numeric arrays:


arrayName.Average, arrayName.Sum
04/04/15

Assignment from Text


Files
Will be covering this in details later, for now just remember
that you can populate an array directly from a text file

Dim strArrayName() As String = IO.File.ReadAllLines(fileName)

A numeric array can be filled from a text file by first filling a


temporary string array with the file and then using a loop,
along with CInt or CDbl, to transfer the numbers into the
numeric array.
Why? Because text file contents are strings.

Text files will need to be put in the bin\Debug folder.


Chapter 7.1, Exercise 45

04/04/15

Practice Problems
Exercises 7.1 (Pg. 285-290)
3, 5, 7, 8, 11, 17, 29

04/04/15

Other Array Operations


.GetUpperBound() is a method that can be used to return the upper
bound of an array. When might you need this?
Remember reading from files!
For i As Integer = 0 To nums.GetUpperBound(0) Note the (0)
lstBox.Items.Add(nums(i))
Next

Relationship between GetUpperBound and Count?


ReDim can be used to resize an array.
Avoid using it its expensive!
A declared arrays data type can not be changed
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

What if you have already assigned the 30 values in the


original grade array and want to preserve those values even
when resizing it to fit in 60 elements?
ReDim Preserve grade(59)

What if we did this instead?


ReDim Preserve grade(19) Last 10 grades will be lost
04/04/15

For Each Loop


Suppose that you want to display scores in a listbox
For i As Integer = 0 To 29
lstBox.Items.Add(grade(i))
Next

Or
For i As Integer = 0 To grade.Count-1
lstBox.Items.Add(grade(i))
Next

Alternative: When we want to iterate through all the array


elements without having to specify the bounds:
For Each val As Double In grade
lstBox.Items.Add(val)
Next

04/04/15

For Each Syntax


For Each variableName As Datatype In arrayName
statement(s)
Next

Datatype has to be the data type of the array


variableName declares the looping variable of that type
During each iteration of the loop, VB sets the variable
variableName to an element in the array and executes
the statement(s)
When all elements of the array have been assigned to the
variable, the For Each Loop terminates
04/04/15

Functions returning
Arrays

Function functionName(var1 As Type1, var2 As Type2,) As DataType()

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)

Assigns to numVar the index of the first occurrence of


the requested value in arrayName
Default value (not matched) is -1
How to find if there are multiple occurrences?
numVar = Array.IndexOf(arrayName, value, startIndex)

04/04/15

Copying an Array
Declared with same Datatype

arrayTwo = arrayOne
arrayTwo references the same array as arrayOne
Same size, contains same data

The two arrays share the same memory


So any change in value of element in one array will
affect the other array
How to make two copies of arrays not share memory?
04/04/15

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)

Comma character is the delimiter for this statement


Why do you need the split method?
PlayerName,Age,Height,Weight,Score

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)

Function Maximum(ages() As Integer) As Integer


Dim max As Integer = ages(0)
For i As Integer = 1 To (ages.Count-1)
If ages(i)>max Then
max=ages(i)
End If
Next
Return max
End Function

Entire arrays are always passed by reference


Any changes to elements of an array passed to a procedure persists
after the procedure terminates
Individual elements of an array can be actually passed by value

04/04/15

Summary (1)
Declaring and assigning values to arrays:
A. Dim students(1) As String
students(0) = Archie
students(1) = Veronica

B. Dim students(1) As String


For i As Integer = 0 To 1
students(i) = InputBox(Enter students name: , Name)
Next
C. Dim students() As String = {Archie, Veronica}
D. Dim students() As String = IO.File.ReadAllLines(StudentList.txt)
E. Dim teamNames(3) As String
Dim line As String = Packers,Packers,Jets,Chiefs
teamNames = line.Split(,c)
04/04/15

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

Quick Recap: Text Files


Writing code to fill arrays can be cumbersome for large arrays
Therefore, we use a simple file called a text file to load large
amounts of data into an array
You can easily edit text files using a program like Notepad or
Visual Studio
Most text files for problems and exercises are provided for you
See the link to data files on the course home page

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

Practice Problems (Chp


7.1)
Solve in class:
Reading from files, displaying array content in a listbox
#56
Using arrays with functions:
#38, #60 (uses Array.IndexOf)
Split method:
#51
Practice at home:
Using arrays with functions:
#33 - #38 (solutions on Moodle)
Use of For Loops:
#55 (solution in the book)
Returning arrays from a function, use of ReDim:
#59 (solution in the book)
04/04/15

Вам также может понравиться