Visual Basic Arrays Topic Structure of the lesson

Visual Basic Arrays

Topic & Structure of the lesson Arrays • Introduction • One Dimensional Array • Sorting an array • Searching an array Visual Basic 2

Learning Outcomes Arrays At the end of this lecture you will be able to : 1. Declare a one dimensional array 2. Store data into an array 3. Use Option Base 4. Declare an Unbound Array 5. Use Specific Bound Arrays Visual Basic 3

Key Words Arrays If you have mastered this topic, you should be able to use the following terms correctly in your assignments and tests: 1. Dim 2. Option Base 3. LBound 4. UBound 5. Index Visual Basic 4

Definition of Arrays An array is a consecutive group of memory locations that all have the same name and the same type To refer to a particular location or element in the array we specify the array name and the index value Visual Basic 5

How do arrays work? Name of Array (all the same) Dim numbers(5) Numbers(0) 56 Numbers(1) 34 Numbers(2) 12 Numbers(3) 32 Numbers(4) 45 Numbers(5) 23 Arrays Only the index number makes the difference Visual Basic 6

Declaring Arrays There are two ways to declare an array: n Default Dim num(10) As Integer n Specified Bounds Dim num(1990 To 2000) As Integer Visual Basic 7

Using Option Base 1 Dim n(5) Private Sub Command 1_Click() For i = 1 To 5 n(i) = Input. Box("enter num") Next i End Sub 1 2 3 4 5 elements Visual Basic Arrays 8

Without Option Base Dim n(5) Private Sub Command 1_Click() For i = 0 To 5 n(i) = Input. Box("enter num") Next i End Sub 012345 Six Elements Visual Basic Arrays 9

Group Exercise Arrays Num(4) 2 1. Write a statement to declare the array 2 Write a statement to to print 8 from the array 1 3 Write a statement to total all elements in the array 3 4 Write a statement to double each element in the array i. e multiply each element by 2 6 5 What is num(0) + num(4) ? 8 Visual Basic 10

Program code using “Default” Arrays Dim num(5) As Integer Arrays Private Sub Command 1_Click() Print "Here are the odd numbers: " For x = 0 To 5 If x Mod 2 = 1 Then num(x) = x End If Print Space$(2) & num(x) Next x End Sub Visual Basic 11

Program code using “Specified Bounds” Arrays Dim frequency(1 To 6), x, die. No As Integer Arrays For x = 1 To 10 die. No = 1 + Int(Rnd() * 6) frequency(die. No) = frequency(die. No) + 1 Next x Print “These are the results of the die roll: ” For x = 1 To 6 Print “No. “ & x & “ = “ & frequency(x) Next x Visual Basic 12

Group Exercise I Arrays Build a program that constructs an array of 20 integers, in which the elements of the array are initialized to the first 20 even numbers. After the initialization process, multiply all the elements of the array with 3. Print the elements of the array before and after the multiplication using two List Boxes. Visual Basic 13

Solution Option Base 1 Dim n(20) As Integer Private Sub Command 1_Click() Dim x , y as Integer y=2 For x = 1 To 20 n(x) = y List 1. Add. Item n(x) y=y +2 Next x Arrays For x = 1 To 20 n(x) = n(x) * 3 List 2. Add. Item n(x) Next x End Sub Visual Basic 14

Example of String Arrays can contain any data types, including strings Option Base 1 Dim Cars(3) As String Dim fastest. Car As Integer Cars(1) = “Proton Satria” Cars(2) = “Nissan Sentra” Cars(3) = “Honda Accord” fastest. Car = 1+ Int(Rnd() * 3) Print “The fastest car is the “ & Cars(fastest. Car) Visual Basic 15

Exercise II Arrays Build a program that constructs an array of 20 integers, initialized with a random number from 1 to 20. Generate another array of integers with the lower bound of 2 and the upper bound of 5. Using this array, find out how many numbers of the 20 integer array are multiples of 2, 3, 4 and 5. Visual Basic 16

Homework Arrays The table below gives names and test scores from a math contest. Write a program to display the names of the students scoring above the average for these eight students. Visual Basic Richard Geraldine James John 135 114 92 91 Paul Max Robert Barbara 150 114 91 124 17

Arrays Visual Basic Arrays Procedures, Searching and Sorting Visual Basic 18

Learning Outcomes Arrays At the end of this lecture you will be able to : 1. Write a program Using LBound and UBound statements 2. Pass an array to a sub procedure 3. Sort an array using bubble sort 4. Search an array using linear search Visual Basic 19

Key Words Arrays If you have mastered this topic, you should be able to use the following terms correctly in your assignments and exams: 1. 2. 3. 4. 5. 6. Visual Basic Dim LBound UBound RND Sort Search 20

LBound and UBound Procedures Arrays LBound and UBound represent the lower boundary and the upper boundary of an array respectively. Example: Dim s(9), x As Integer For x = LBound(s) To UBound(s) For x = 0 To 9 s(x) = 2 + 2 * x Next x For x = LBound(s) To UBound(s) print space$(2) & x & space$(7) & s(x) Next x Visual Basic 21

Group Exercise Arrays Build a program that constructs an array of 20 integers, initialized with a random number from 1 to 20. Create another array of integers with the lower bound of 2 and the upper bound of 5. Using this array, find out how many numbers of the 20 integer array are multiples of 2, 3, 4 and 5. Visual Basic 22

Solution Dim num(1 to 20) As Integer Dim a(2 To 5) As Integer Private Sub Command 1_Click() Dim x As Integer, j As Integer For x = LBound(num) To UBound(num) num(x) = 1 + Int(Rnd * 20) Next x Arrays For j = 1 To 20 If num(j) Mod 2 = 0 Then a(2) = a(2) + 1 End If If num(j) Mod 3 = 0 Then a(3) = a(3) + 1 End If Visual Basic 23

Solution If num(j) Mod 4 = 0 Then Arrays a(4) = a(4) + 1 End If If num(j) Mod 5 = 0 Then a(5) = a(5) + 1 End If Next j Print “Multiple of Two’s" & a(2) Print “Multiple of Three’s" & a(3) Print “Multiple of Four’s" & a(4) Print “Multiple of Five’s & a(5) End Sub Visual Basic 24

Passing Arrays to Procedures For a procedure to receive an array through Arrays a call, the parameter list must specify that an array will be received. For example: Private Sub Process. Array(x() As Integer) The following call passes array Months to the above procedure: Call Process. Array(Months()) Remember: Arrays are passed by reference, not value! Visual Basic 25

Example of an Array Program using Procedures Arrays Dim num(1 To 30) As Integer Dim y As Integer Private Sub Form_Load() Call Initialize. Array(num()) Call Update. Values(num()) End Sub Visual Basic 26

Example of an Array Program using Procedures Private Sub Initialize. Array(x() As Integer) Arrays For y = 1 To 30 x(y) = 1 + Int(Rnd() * 10) List 1. Add. Item x(y) Next y End Sub Private Sub Update. Values(x() As Integer) For y = 1 To 30 x(y) = x(y) * x(y) List 2. Add. Item x(y) Next y End Sub Visual Basic 27

Group Exercise Arrays Write a program that will pass an array of 10 integers to a sub program. The sub program will initialize the array to a random number from 1 to 10. Visual Basic 28

Sorting Arrays The simplest way to sort an array is through a bubble sort. X(1) 5 X(1) 3 X(2) 5 Temp = X(1) Step 1 Visual Basic X(1) = X(2) Step 2 X(2) = Temp Step 3 29

Program that Sorts Arrays Private Sub Command 1_Click() Dim num(1 To 10) As Integer Arrays Dim y, max. No, temp As Integer For y = 1 To 10 num(y) = 1 + Int(Rnd() * 100) Next y For max. No = 1 To 10 Step 1 For y = 1 To 9 Step 1 If num(y) > num(y + 1) Then temp = num(y) = num(y + 1) = temp End If Next y Next max. No Visual Basic 30

Group Exercise Arrays Write a program to sort the following array into descending order 1578903264 After Sorting 9876543210 Visual Basic 31

Searching Arrays There are two ways to search through an array: n Linear Search Compares each element with the search key n Binary Search Eliminates searching through redundant arrays by comparing the search key with the middle element (array must be sorted) Visual Basic 32

Program Using Linear Search Dim a(1 to 10) As Integer Arrays Dim x, key As Integer For x = 1 to 10 a(x) = val(Inputbox(“Enter Num”) Next x key = val(Inputbox(“Enter Num to Search”) For x = LBound(a) To UBound(a) If a(x) = key Print “Found!” Exit Sub End If Next x Print “Not Found!” Visual Basic 33

Group Exercise Arrays § Write a program to store 10 random numbers into an array called Num § Accept a value from the user using an Input. Box § Search the array to find the value § If the number is found display using Msg. Box “Number Found” otherwise display “Not Found” Visual Basic 34

Program Using Binary Search Dim a(1 to 10), x, low, middle, high, key As Integer Arrays For x = 1 to 10 a(x) = val(Inputbox(“Enter Num”) Next x key = val(Inputbox(“Enter Num to Search”) low = LBound(a) high = UBound(a) Do While (low <= high) middle = (low + high) 2 If (key = a(middle)) Then Print “Found” Exit Sub Else Visual Basic 35

Program Using Binary Search (cont) Arrays If (key < a(middle) Then high = middle – 1 Else low = middle + 1 End If Loop Print “Not found” Visual Basic 36

Group Exercise The table below gives names and test scores from a math. Arrays contest. 1. Write a program to store the names and marks into an array 2. Display the names of the students scoring above the average mark Visual Basic Richard 135 Geraldine 114 James 92 John 91 Paul 150 Max 114 Robert 91 Barbara 124 37

Multi-dimensional Arrays While single dimensional arrays look like this: A B C D E A two-dimensional array looks like this: Visual Basic A 1 B 1 C 1 D 1 E 1 A 2 B 2 C 2 D 2 E 2 38

Declaring a Multi-dimensional Array 0 1 2 3 4 5 6 7 0 1 2 3 Arrays If we were to represent a chess board using a multi-dimensional array, we will have the following declaration: 4 5 6 7 Visual Basic Dim chess(8, 8) As Integer Red square: chess(5, 4) 39

Declaring a Multi-dimensional Array (II) 1 2 3 4 5 6 7 8 Arrays 1 2 Or… to be more specific: 3 4 Dim chess(1 To 8, 1 To 8) As Integer 5 6 7 8 Visual Basic Red square: chess(6, 5) 40

Multi-Dimensional Arrays Option explicit ‘store values into a two dimensional array Dim n(1 to 2, 1 to 3) As Integer Private Sub Command 1_Click() For i = 1 To 2 For j = 1 To 3 n(i, j) = Val(Input. Box(“Enter Num" & “Row” & i & “Col” & j)) Next j Next i ‘display contents of the array to listbox For i = 1 To 2 For j = 1 To 3 List 1. Add. Item n(i, j) Next j Next i End Sub Visual Basic 41

Exercise Arrays The scores for the top three golfers at the 1999 golf tournament are shown in table below Round 1 2 3 4 Tiger Woods 70 66 65 69 Tom Kite 77 69 66 70 Tommy Tolles 72 72 72 67 • Write a procedure to enter the data to an array • Write a program to compute the total score for each player Visual Basic 42

Solution Dim nom(1 to 3) as string, score (1 to 3, 1 to 4) as integer Private sub command 1_click() Dim player, round, total as integer For player = 1 to 3 nom(player) = inputbox(“enter name”) for round 1 = 1 to 4 nom(player, round) = val(inputbox(“enter score”)) next round Next player ‘compute score for each payer For player = 1 to 3 let total = 0 For round = 1 to 4 let total = total + score(player, round) Next round Pic 1. print “The total score for” ; nom(player); “is’’; total Next player Visual Basic Arrays 43

Control Arrays • • Group together similar function controls Min Lower Bound 0 and Max 32767 Identified by an Integer Index Example Text 1(0). text = “Welcome To VB” Text 1(1). text = “Welcome To VB” Visual Basic 44

Homework Arrays • Write a program to store random numbers from 1 to 10 into a one dimensional array and determine the largest number Visual Basic 45

Homework Arrays 100 students were asked to rate the quality of a particular lecturer in their class. They give a rating on a scale of 1 to 10 (1 being terrible and 10 being excellent). Place the 100 responses in an array of integers and summarize the results of the poll. Note: The responses are to be randomized. Visual Basic 46

Solution Arrays Dim frequency(1 To 10), x, poll As Integer Private Sub Command 1_Click() For x = 1 To 100 poll = 1 + Int(Rnd() * 10) frequency(poll) = frequency(poll) + 1 Next x Print "These are the results of the poll: " For x = 1 To 10 Print "No. " & x & " = " & frequency(x) Next x End Sub Visual Basic 47
- Slides: 47