Notes
Slide Show
Outline
1
Chapter 7 – Arrays
  • 7.1 Creating and Accessing Arrays
  • 7.2 Using Arrays
  • 7.3 Some Additional Types of Arrays
  • 7.4 Sorting and Searching
  • 7.5 Two-Dimensional Arrays
2
7.1 Creating and Accessing Arrays
  • ReDim Statement
  • Using an Array as a Frequency Table
3
Simple 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.
4
Example
  • Suppose that you want to evaluate the exam
    grades for 30 students and to display the names of the students whose scores are above average.


  • Private Sub btnDisplay_Click(...)
  •     Handles btnDisplay.Click
    Dim student1 As String, score1 As Double
    Dim student2 As String, score2 As Double
    Dim student3 As String, score3 As Double
5
Using Arrays
  • Dim student(30) As String
  • Dim score(30) As Double
6
Putting Values into an Array
  • student(1) = "Tom Brown"
7
Array 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
8
Example 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
9
Output Example 1
10
Example 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
11
Initializing 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"}
12
ReDim 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.
13
Preserve
  • To keep any data that has already been stored in the array when resizing it, use
  • ReDim Preserve arrayName(m)
14
Using 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 >= "A") And (letter <= "Z") Then
  •       index = Asc(letter) - 64 'The ANSI value of "A" is 65
  •       charCount(index) += 1
  •     End If
  •   Next
15
Example 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) > 0 Then
  •       lstCount.Items.Add(letter & " " & _
  •                charCount(index))
  •     End If
  •   Next
  • End Sub
16
Example 4 Output
17
Out 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)
18
Copying 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.


19
7.2 Using Arrays
  • Ordered Arrays
  • Using Part of an Array
  • Merging Two Ordered Arrays
  • Passing Arrays to Procedures
20
Ordered Arrays
  • An array is ordered if the elements are in ascending or descending order.
21
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) >= name2Find) Or (n = 10)
  •   If nom(n) = name2Find Then
  •     txtResult.Text = "Found."
  •   Else
  •     txtResult.Text = "Not found."
  •   End If
  • End Sub
22
Output Example 1
23
Flow Chart Search of Ordered Array
24
Using Part of an Array
  • 'Demonstrate using part of an array
  • Dim stock(100) As String
  • Dim counter As Integer
  • Private Sub btnRecord_Click(...) Handles btnRecord.Click
  •   If (counter < 100) Then
  •     counter += 1 'Increment counter by 1
  •     stock(counter) = txtCompany.Text
  •     txtCompany.Clear()
  •     txtCompany.Focus()
  •     txtNumber.Text = CStr(counter)
  •   Else
  •     MsgBox("No space to record additional companies.", , "")
  •     txtCompany.Clear()
  •     btnsummarize.Focus()
  •   End If
  • End Sub
25
Example 2 continued
  • Private Sub btnsummarize_Click(...)
  •     Handles btnsummarize.Click
  •   'List stock companies that have been recorded
  •   Dim i As Integer
  •   lstStocks.Items.Clear()
  •   For i = 1 To counter
  •     lstStocks.Items.Add(stock(i))
  •   Next
  • End Sub
26
Example 2 output
27
Merging Two Ordered Arrays
  • To consolidate two lists into a single ordered list:
  •  Compare the two names at the top of the first and second lists.
    • If one name alphabetically precedes the other, copy it onto the third list and cross it off its original list.
    • If the names are the same, copy the name onto the third list and cross out the name from the first and second lists.
  • Repeat Step 1 with the current top names until you reach the end of either list.
  • Copy the names from the remaining list onto the third list.
28
Passing 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
29
Example 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
30
Comments
  • Searching successive elements of an ordered list beginning with the first element is called a sequential search.
31
Passing 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
32
7.3 Some Additional Types of Arrays
  • Control Arrays
  • Array of Structures
33
Control 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
34
Control Arrays continued
  • The following statements declare control arrays.
  • Dim lblTitle(10) As Label
  • Dim txtNumber(8) As TextBox
  • Dim btnAmount() As Button
35
Example 1
  • 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
36
Example 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
37
Example 1 Output
38
Structures
  • A way of grouping heterogeneous data together
  • Also called a UDT (User Defined Type)
  • Sample structure definition:
    • Structure College
    •   Dim name As String
    •   Dim state As String
    •   Dim yearFounded As Integer
    • End Structure
39
Structure Definition
  • Each subvariable in a structure is called a member or field
  • To declare a variable of a structure type:
  • Dim college1 As College
  • Each member is accessed via the variable name dot member name
  • college1.name = "Harvard"
40
Example 2
  • Structure College
  •   Dim name As String
  •   Dim state As String
  •   Dim yearFounded As Integer
  • End Structure
  • Dim college1, college2, collegeOlder As College
  • Private Sub btnFirst_Click(...) Handles btnFirst.Click
  •   Dim prompt As String
  •   college1.name = InputBox("Enter name of college.", "Name")
  •   college1.state = InputBox("Enter state.", "State")
  •   prompt = "Enter the year the first college was founded."
  •   college1.yearFounded = CInt(InputBox(prompt, "Year"))
  • End Sub
41
Structure Members
  • Integer, String, Double, etc.
  • Another User Defined Type
  • Arrays
    • Must not specify range
    • Range must be set using ReDim
42
Example 4
  • Structure FullName
  •   Dim firstName As String
  •   Dim lastName As String
  • End Structure
  • Structure Student
  •   Dim name As FullName
  •   Dim credits() As Integer
  • End Structure
  • Private Sub btnGet_Click(...) Handles btnGet.Click
  •   Dim numYears, i As Integer
  •   Dim person As Student
43
Example 4 continued
  •   txtResult.Clear()
  •   person.name.firstName = InputBox("First Name:")
  •   person.name.lastName = InputBox("Second Name:")
  •   numYears = CInt(InputBox("Number of years " & _
  •                   "completed:"))
  •   ReDim person.credits(numYears)
  •   For i = 1 To numYears
  •     person.credits(i) = CInt(InputBox("Credits in yr "_
  •                              & i))
  •   Next
  •   DetermineStatus(person)
  • End Sub
44
Example 4 continued
  • Sub DetermineStatus(ByVal person As Student)
  •   Dim i, total As Integer
  •   For i = 1 To person.credits.GetUpperBound(0)
  •     total += person.credits(i)
  •   Next
  •   If (total >= 120) Then
  •     txtResult.Text = person.name.firstName & " " & _
  •        person.name.lastName & " has enough credits" & _
  •        " to graduate."
  •   Else
  •     txtResult.Text = person.name.firstName & " " & _
  •        person.name.lastName & " needs " & _
  •        (120 - total) & " more credits to graduate."
  •   End If
  • End Sub


45
7.4 Sorting and Searching
  • Bubble Sort
  • Shell Sort
  • Searching
46
Sorting
  • Sorting is an algorithm for ordering an array.
  • We discuss two sorting algorithms:
    • bubble sort
    • Shell sort
  • Both use the swap algorithm:
    • temp = varl
    • varl = var2
    • var2 = temp
47
Example 1 Swap Algorithm
  • Private Sub btnAlphabetize_Click(...) _
  •     Handles btnAlphabetize.Click
  •   Dim firstWord, secondWord, temp As String
  •   firstWord = txtFirstWord.Text
  •   secondWord = txtSecondWord.Text
  •   If (firstWord > secondWord) Then
  •     temp = firstWord
  •     firstWord = secondWord
  •     secondWord = temp
  •   End If
  •   txtResult.Text = firstWord & " before " & _
  •                    secondWord
  • End Sub
48
Bubble Sort Algorithm
  • Compare the first and second items. If they are out of order, swap them.
  • Compare the second and third items. If they are out of order, swap them.
  • Repeat this pattern for all remaining pairs. The final comparison and possible swap are between the next-to-last and last elements.
49
Shell Sort Algorithm
  • Begin with a gap of g = Int(n/2)
  • Compare items 1 and 1 + g, 2 and 2 + g, . . ., n and n - g. Swap any pairs that are out of order.
  • Repeat Step 2 until no swaps are made for gap g.
  • Halve the value of g.
  • Repeat Steps 2, 3, and 4 until the value of g is 0.
50
Searching
  • Sequential search starts at the beginning of a list and keeps looking one by one until the item is found or the end of the list is reached.
  • For a sequential search, the list need not be sorted.
51
Binary Search
  • Usually more efficient than sequential search
  • List must be sorted
52
Algorithm for Binary Search
  • Denote the subscript of the first item in the  list by first and the subscript of the last item by last. Initially, the value of first is 1, the value of last is the number of items in the list, and the value of flag is False.
  • Look at the middle item of the current list, the item having the subscript  middle = Int((first + last ) / 2)
  • If the middle item is quarry (what you are looking for), then flag is set to True and the search is over.
  • If the middle item is greater than quarry, then quarry should be in the first half of the list. So the subscript of quarry must lie between first and middle - 1. That is,the new value of last is middle - 1.
53
Algorithm continued
  • If the middle item is less than quarry, then quarry should be in the second half of the list of possible items. So the subscript of quarry must lie between middle +1 and last. That is, the new value of first is middle +1.
  • Repeat Steps 2 through 5 until quarry is found or until the halving process uses up the entire list. (When the entire list has been used up, first > last.) In the second case, quarry was not in the original list.


54
7.5 Two dimensional arrays
  • One-dimensional arrays require one subscript to access each element in the array.
  • Two-dimensional arrays require two subscripts to access each element.
  • Dim rm(4, 4) As Double
55
Populating a Two-Dimensional Array
  • Dim rm(4, 4) As Double
  • Private Sub Form1_Load(...) Handles MyBase.Load
  • 'Fill two-dimensional array with intercity mileages
  •   Dim sr As IO.StreamReader =
  •             IO.File.OpenText("DISTANCE.TXT")
  •   Dim row, col As Integer
  •   For row = 1 To 4
  •     For col = 1 To 4
  •       rm(row, col) = CDbl(sr.ReadLine)
  •     Next
  •   Next
  •   sr.Close()
  • End Sub
56
Notes on Two-Dimensional Arrays
  • An unsized two-dimensional array can be declared with a statement of the form
  • Dim arrayName(,) As varType
  • and a two-dimensional array can be declared and initialized at the same time with a statement of the form
  • Dim arrayName(,) As varType = {{ROW0}, {ROW1},... {ROWm}}
57
ReDim and Two-Dimensional Arrays
  • An already-created array can be resized
  • ReDim arrayName(r, s)
  • which loses the current contents, or with
  • ReDim Preserve arrayName(m, s)
  • When Preserve is used, only the column can be resized.
  • ReDim cannot change the number of dimensions in an array.


58
Chapter 7 – Array Summary
  • 7.1 Creating and Accessing Arrays
  • 7.2 Using Arrays
    • Passing arrays to functions and sub procedures
  • 7.3 Some Additional Types of Arrays
    • Structures and arrays of structures
    • Merging two ordered arrays
  • 7.4 Sorting and Searching
    • Linear and binary searches
    • Exchange sorts
  • 7.5 Two-Dimensional Arrays