Title: Chapter 7
1Chapter 7 Arrays
- 7.1 Creating and Accessing Arrays
- 7.2 Using Arrays
- 7.3 Control Arrays
- Skip Structures (7.3), 7.4 and 7.5
27.1 Creating and Accessing Arrays
- Array Creation
- ReDim Statement
- Using an Array as a Frequency Table
3Simple variables
- A variable (or simple variable) is a name to
which VB.NET can assign a single value. - An array variable is a collection of simple
variables of the same type to which VB.NET can
efficiently assign a list of values.
4Elements of an Array
- Array Name A valid variable name for the
structure. - Subscript or Index A value that refers to a
particular array element. - Element An individual data item within an array.
5Example
- Suppose that you want to evaluate the examgrades
for 30 students and to display the names of the
students whose scores are above average. - Private Sub btnDisplay_Click(...)
- Handles btnDisplay.ClickDim student1 As
String, score1 As DoubleDim student2 As String,
score2 As DoubleDim student3 As String, score3
As Double
6Using Arrays
Upper bound of subscripts in the array
- Dim student(30) As String
- Dim score(30) As Double
Array name
Data type
7Putting Values into an Array
subscript
Read "student sub one equals Tom Brown" Which
means that the string "Tom Brown" is being stored
at the second location in the array called
student because all arrays begin counting at 0.
8Array Terminology
- Dim arrayName(n) As DataType
- 0 is the "lower bound" of the array
- n is the "upper bound" of the array the last
available subscript in this array - The number of elements is the size of the array
9Variable Arrays
- Can have one or two dimensions
- A one-dimensional array is simply a row (or
column) of variables - Each element in an array is identified by a
subscript - You refer to an array element by the arrays name
followed by the elements subscript
10One-dimensional Array
State(3)
State(4)
State(5)
State(1)
State(2)
State(0)
Tennessee
Nebraska
New Jersey
New Mexico
Texas
State(0)
Nebraska
State(1)
New Jersey
State(2)
New Mexico
State(3)
Tennessee
State(4)
Demo Provinces
State(5)
Texas
11Example 1
- Private Sub btnWhoWon_Click(...) _
- Handles btnWhoWon.Click
- Dim teamName(4) As String
- Dim n As Integer
- 'Place Super Bowl Winners into the array
- teamName(1) "Packers"
- teamName(2) "Packers"
- teamName(3) "Jets"
- teamName(4) "Chiefs"
- 'Access array
- n CInt(txtNumber.Text)
- txtWinner.Text teamName(n)
- End Sub
12Output Example 1
13Example 2
- Dim teamName(3) As String
- Private Sub btnWhoWon_Click(...)Handles
btnWhoWon.Click - Dim n As Integer
- n CInt(txtNumber.Text)
- txtWinner.Text teamName(n)
- End Sub
- Private Sub Form1_Load(...) Handles MyBase.Load
- 'Place Super Bowl Winners into the array
- teamName(1) "Packers"
- teamName(2) "Packers"
- teamName(3) "Jets"
- End Sub
14Initializing Arrays
- Arrays may be initialized when they are created
- Dim arrayName() As varType value0, _
- value1, value2, ..., valueN
- declares an array having upper bound N and
assigns value0 to arrayName(0), value1 to
arrayName(1), value2 to arrayName(2), ..., and
valueN to arrayName(N). - Dim teamName() As String "", "Packers", _
- "Packers", "Jets", "Chiefs"
15Initializing an Array by Reading from a File
- Dim student (30) As String, count as integer
- Dim sr as IO.streamreader IO.File.OpenText
- Open STUDENTS.TXT For Input As 1
- For count 1 To 30
- student ( count ) sr.readline
- Next
- sr.close
- Demo Provinces2
16Parallel Arrays
- Two arrays are referred to as parallel if
subscripted variables having the same subscript
(elements) are related. - i.e. student(30) and grade(30)
17The Average Program Revisited!
- For count 1 To 30
- student (count) sr.readline
- grade (count) Cdbl(sr.readline)
- Next
- sum 0
- For count 1 To 30
- sum grade(count)
- Next
- average sum/30
18Unknown Array Size
- What do I do if I dont know the size of a file
and thus the size of the array??
19First Technique Unknown Size
- Dim Array with no upper bound
- Use a loop and counter to count the number of
items in the file - ReDim the array based on the counter
- Use a second loop to then read the known file size
20Second Technique Unknown Size
- Dim Array with a large upper bound
- Use a loop and sr.peek to see if additional data
exists in the file - Use ReDim Preserve to increase the upper bound of
the array by one - Read one piece of data into the new array element
just created
21Third Technique Unknown Size
- Dim an Array with a large upper bound (large
enough to easily hold all data) - Read from the file into the array using a loop
with a counter - Keep track of the number of pieces of data in the
array with the counter - So in effect, you only use part of a large array
22ReDim Statement
- The size of an array may be changed after it is
created - ReDim arrayName(m)
- where arrayName is the name of the already
declared array and m is an Integer
literal,variable, or expression.
23Preserve
- To keep any data that has already been stored in
the array when resizing it, use - ReDim Preserve arrayName(m)
24Using an Array as a Frequency Table
- Private Sub btnAnalyze_Click(...) Handles
btnAnalyze.Click - 'Count occurrences of the various letters in a
sentence - Dim index, letterNum As Integer
- Dim sentence, letter As String
- Dim charCount(26) As Integer
- 'Examine and tally each letter of the sentence
- sentence (txtSentence.Text).ToUpper
- For letterNum 1 To sentence.Length
- letter sentence.Substring(letterNum - 1, 1)
- If (letter gt "A") And (letter lt "Z") Then
- index Asc(letter) - 64 'The ANSI value of
"A" is 65 - charCount(index) 1
- End If
- Next
25Example 4 continued
- 'List the tally for each letter of alphabet
- lstCount.Items.Clear()
- For index 1 To 26
- letter Chr(index 64)
- If charCount(index) gt 0 Then
- lstCount.Items.Add(letter " " _
- charCount(index))
- End If
- Next
- End Sub
26Example 4 Output
27Out of Bounds Error
- The following sets up an array, and then
references an element that doesn't exist. This
will cause an error. - Dim trees() As String "", "Sequoia", _
- "Redwood", "Spruce"
- txtBox.Text trees(5)
28Copying Arrays
- If arrayOne() and arrayTwo() have been declared
with the same data type, then the statement - arrayOne arrayTwo
- makes arrayOne() an exact duplicate of
arrayTwo(). It will have the same size and
contain the same information.
29Exercises p. 312In-class P. 319, 36
307.2 Using Arrays
- Ordered Arrays
- Using Part of an Array
- Merging Two Ordered Arrays
- Passing Arrays to Procedures
31Ordered Arrays
- An array is ordered if the elements are in
ascending or descending order. - Why would we want to order an array??
32Ordered Arrays - Example 1
- Dim nom() As String "", "AL", "BOB", "CARL",
"DON","ERIC", _ - "FRED", "GREG", "HERB", "IRA", "JACK"
- Private Sub btnSearch_Click(...) Handles
btnSearch.Click - Dim name, name2Find As String
- Dim n As Integer 'Subscript of the array
- name2Find txtName.Text.ToUpper
- Do
- n 1 'Add 1 to n
- Loop Until (nom(n) gt name2Find) Or (n 10)
- If nom(n) name2Find Then
- txtResult.Text "Found."
- Else
- txtResult.Text "Not found."
- End If
- End Sub
33Ordered Arrays
- Answer It makes searching them much more
efficient - On average, you only have to search half an array
that is ordered whereas you have to search the
whole array if unordered
34Merging Two Ordered Arrays
- To consolidate two lists into a single ordered
list - Compare the two names (numbers) at the top of
the first and second lists. - If one name (number) precedes the other, copy it
onto the third list and cross it off its original
list. - If the names (numbers) are the same, copy the
name (number) onto the third list and cross out
the name (number) from the first and second
lists. - Repeat Step 1 with the current top names
(numbers) until you reach the end of either list. - Copy the names from the remaining list onto the
third list.
35Passing Arrays to Procedures
- An array declared in a procedure is local to that
procedure - An entire array can be passed to a Sub or
Function procedure
36Example 4
- Private Sub btnCompute_Click(...) Handles
btnCompute.Click - Dim score() As Integer 0, 85, 92, 75, 68,
84, 86, _ - 94, 74, 79, 88
- txtAverage.Text CStr(Sum(score) / 10)
- End Sub
- Function Sum(ByVal s() As Integer) As Integer
- Dim total, index As Integer
- total 0
- For index 1 To s.GetUpperBound(0) 'The upper
bound is 10 - total s(index)
- Next
- Return total
- End Function
37Comments
- Searching successive elements of an ordered list
beginning with the first element is called a
sequential search.
38Passing an Array Element
- A single element of an array can be passed to a
procedure just like any ordinary numeric or
string variable. - Private Sub btnDisplay_Click(...) Handles
btnDisplay.Click - Dim num(20) As Integer
- num(5) 10
- lstOutput.Items.Add(Triple(num(5)))
- End Sub
- Private Function Triple(ByVal x As Integer) As
Integer - Return 3 x
- End Function
397.3 Some Additional Types of Arrays
- Control Arrays
- Array of Structures (OMIT)
40Control Arrays
- Control arrays are arrays of controls, such as
labels, text boxes, etc. - They are created in much the same way as any
other array - Dim arrayName(n) As ControlType
- or
- Dim arrayName() As ControlType
41Control Arrays continued
- The following statements declare control arrays.
- Dim lblTitle(10) As Label
- Dim txtNumber(8) As TextBox
- Dim btnAmount() As Button
42Example 1
Array of controls
- Dim lblDept(5) As Label
- Dim txtDept(5) As TextBox
- Private Sub Form1_Load(...) Handles MyBase.Load
- Dim depNum As Integer
- lblDept(1) Label1
- lblDept(2) Label2
- lblDept(3) Label3
- lblDept(4) Label4
- lblDept(5) Label5
- txtDept(1) TextBox1
- txtDept(2) TextBox2
- txtDept(3) TextBox3
- txtDept(4) TextBox4
- txtDept(5) TextBox5
Placing controls Into arrays
43Example 1 continued
- For depNum 1 To 5
- lblDept(depNum).Text "Department " depNum
- txtDept(depNum).Clear()
- Next
- End Sub
- Private Sub btnCompute_Click(...)
- Handles btnCompute.Click
- Dim totalSales As Double 0
- Dim depNum As Integer
- For depNum 1 To 5
- totalSales CDbl(txtDept(depNum).Text)
- Next
- txtTotal.Text FormatCurrency(totalSales)
- End Sub
44Example 1 Output
45 46ListBoxes
- Adding to a listbox
- Listboxes as arrays
- Events associated with listboxes
47Useful Properties of the List Box
- Items can be placed into a listbox at design time
or runtime - lstBox.items.add(item1)
- lstBox.items.add(item2)
- This forms an array with 2 elements
- For the index number of the currently highlighted
item - lstBox.SelectedIndex
48More List Box Properties
- lstBox.Items() is the list of items in the list
box. The value of the item with an index of "n"
is - lstBox.Items(n)
- The data type of the elements in the
lstBox.Items() array is Object. To put the first
element of lstBox.Items in a text box - txtBox.Text CStr(lstBox.Items(0))
49Currently Highlighted Item in a List Boxes
- The currently highlighted item can be obtained
by - lstBox.Items(lstBox.SelectedIndex)
- Or
- lstBox.Text
- Or
- lstBox.SelectedItem
50List Box Events
- Three main types of events with list boxes
- Click if the user clicks on an item in the list
box - SelectedIndexChanged (default event) if the
user clicks on an item or uses the arrow keys to
select it - DoubleClick - if the user double-clicks on an item
Demo - Movies
51The Random Class
- A random number generator declared with the
statement - Dim randomNum As New Random()
- If m and n are whole numbers and m lt n then the
following generates a whole number between m and
n (including m, but excluding n) - randomNum.Next(m, n)
Demo Random