arrays

Post on 03-Dec-2014

90 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Arrays

Visual Basic

Visual Basic Slide 2 of 48

Arrays

Topic & Structure of the lesson

•Introduction

•One Dimensional Array

•Sorting an array

•Searching an array

Visual Basic Slide 3 of 48

Arrays

Learning Outcomes

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 Slide 4 of 48

Arrays

Key Words

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 Slide 5 of 48

Arrays

References

• An Introduction to Programming Using Visual Basic 6.0

David I Schneider

Chapter 7

• VB 6 How to Program

Deitel and Deitel

Chapter 7

Visual Basic Slide 6 of 48

Arrays

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 Slide 7 of 48

Arrays

How do arrays work?

56

34

12

32

45

23

Numbers(0)

Numbers(1)

Numbers(2)

Numbers(3)

Numbers(4)

Numbers(5)

Name of Array (all the same)

Only the index number makes the difference

Dim numbers(5)

Visual Basic Slide 8 of 48

Arrays

Declaring Arrays

There are two ways to declare an array:

Default

Specified Bounds

Dim num(10) As Integer

Dim num(1990 To 2000) As Integer

Visual Basic Slide 9 of 48

Arrays

Using Option Base

Option Base 1

Dim n(5)

Private Sub Command1_Click()

For i = 1 To 5

n(i) = InputBox("enter num")

Next i

End Sub

1 2 3 4 5 elements

Visual Basic Slide 10 of 48

Arrays

Without Option Base

Dim n(5)

Private Sub Command1_Click()

For i = 0 To 5

n(i) = InputBox("enter num")

Next i

End Sub

0 1 2 3 4 5 Six Elements

Visual Basic Slide 11 of 48

Arrays

Group Exercise

Num(4)2

1

3

6

8

1. Write a statement to declare the array

2 Write a statement to to print 8 from the array

3 Write a statement to total all elements in the array

4 Write a statement to double each element in the array i.e multiply each element by 2

5 What is num(0) + num(4) ?

Visual Basic Slide 12 of 48

Arrays

Program code using “Default” Arrays

Dim num(5) As Integer

Private Sub Command1_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 Slide 13 of 48

Arrays

Program code using “Specified Bounds” Arrays

Dim frequency(1 To 6), x, dieNo As Integer

For x = 1 To 10

dieNo = 1 + Int(Rnd() * 6)

frequency(dieNo) = frequency(dieNo) + 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 Slide 14 of 48

Arrays

Group Exercise I

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 Slide 15 of 48

Arrays

SolutionOption Base 1Dim n(20) As IntegerPrivate Sub Command1_Click()Dim x ,y as Integery = 2For x = 1 To 20 n(x) = y List1.AddItem n(x) y = y + 2Next x

For x = 1 To 20 n(x) = n(x) * 3 List2.AddItem n(x)Next xEnd Sub

Visual Basic Slide 16 of 48

Arrays

Example of String Arrays

Arrays can contain any data types, including stringsOption Base 1

Dim Cars(3) As String

Dim fastestCar As Integer

Cars(1) = “Proton Satria”

Cars(2) = “Nissan Sentra”

Cars(3) = “Honda Accord”

fastestCar = 1+ Int(Rnd() * 3)

Print “The fastest car is the “ & Cars(fastestCar)

Visual Basic Slide 17 of 48

Arrays

Exercise II

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 Slide 18 of 48

Arrays

Homework

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.

Richard 135

Geraldine 114

James 92

John 91

Paul 150

Max 114

Robert 91

Barbara 124

Visual Basic Slide 19 of 48

Arrays

Visual Basic

Arrays

Procedures, Searching and Sorting

Visual Basic Slide 20 of 48

Arrays

Learning Outcomes

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 Slide 21 of 48

Arrays

Key Words

If you have mastered this topic, you should be able to use the following terms correctly in your assignments and exams:

1. Dim

2. LBound

3. UBound

4. RND

5. Sort

6. Search

Visual Basic Slide 22 of 48

Arrays

LBound and UBound Procedures

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)

s(x) = 2 + 2 * x

Next x

For x = LBound(s) To UBound(s)

print space$(2) & x & space$(7) & s(x)

Next x

For x = 0 To 9

Visual Basic Slide 23 of 48

Arrays

Group Exercise

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 Slide 24 of 48

Arrays

Solution

Dim num(1 to 20) As Integer

Dim a(2 To 5) As Integer

Private Sub Command1_Click()

Dim x As Integer, j As Integer

For x = LBound(num) To UBound(num)

num(x) = 1 + Int(Rnd * 20)

Next x

For j = 1 To 20If num(j) Mod 2 = 0 Then a(2) = a(2) + 1End IfIf num(j) Mod 3 = 0 Then a(3) = a(3) + 1End If

Visual Basic Slide 25 of 48

ArraysIf num(j) Mod 4 = 0 Then

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

Solution

Visual Basic Slide 26 of 48

Arrays

Passing Arrays to Procedures

For a procedure to receive an array through a call, the parameter list must specify that an array will be received. For example:

Private Sub ProcessArray(x() As Integer)

The following call passes array Months to the above procedure:

Call ProcessArray(Months())

Remember: Arrays are passed by reference, not value!

Visual Basic Slide 27 of 48

Arrays

Example of an Array Program using Procedures

Dim num(1 To 30) As Integer

Dim y As Integer

Private Sub Form_Load()

Call InitializeArray(num())

Call UpdateValues(num())

End Sub

Visual Basic Slide 28 of 48

ArraysPrivate Sub InitializeArray(x() As Integer)

For y = 1 To 30

x(y) = 1 + Int(Rnd() * 10)

List1.AddItem x(y)

Next y

End Sub

Private Sub UpdateValues(x() As Integer)

For y = 1 To 30

x(y) = x(y) * x(y)

List2.AddItem x(y)

Next y

End Sub

Example of an Array Program using Procedures

Visual Basic Slide 29 of 48

Arrays

Group Exercise

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 Slide 30 of 48

Arrays

Sorting Arrays

The simplest way to sort an array is through a bubble sort.

X(1) 5

X(2) 3

Temp

5

X(1) 3

X(2) 3

Temp

5

X(1) 3

X(2) 5

Temp

5

Temp = X(1) X(1) = X(2) X(2) = Temp

Step 1 Step 2 Step 3

Visual Basic Slide 31 of 48

Arrays

Program that Sorts Arrays

Private Sub Command1_Click()

Dim num(1 To 10) As Integer

Dim y, maxNo, temp As Integer

For y = 1 To 10

num(y) = 1 + Int(Rnd() * 100)

Next y

For maxNo = 1 To 10 Step 1

For y = 1 To 9 Step 1

If num(y) > num(y + 1) Then

temp = num(y)

num(y) = num(y + 1)

num(y + 1) = temp

End If

Next y

Next maxNo

Visual Basic Slide 32 of 48

Arrays

Group Exercise

Write a program to sort the following array

into descending order

1 5 7 8 9 0 3 2 6 4

After SortingAfter Sorting

9 8 7 6 5 4 3 2 1 0

Visual Basic Slide 33 of 48

Arrays

Searching Arrays

There are two ways to search through an array:

Linear Search

Binary Search

Compares each element with the search key

Eliminates searching through redundant arrays by comparing the search key with the middle element (array must be sorted)

Visual Basic Slide 34 of 48

Arrays

Program Using Linear Search

Dim a(1 to 10) As Integer

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 Slide 35 of 48

Arrays

Group Exercise

Write a program to store 10 random numbers into an array called Num

Accept a value from the user using an InputBox

Search the array to find the value If the number is found display using MsgBox

“Number Found” otherwise display “Not Found”

Visual Basic Slide 36 of 48

Arrays

Program Using Binary Search

Dim a(1 to 10),x, low, middle, high, key As Integer

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 Slide 37 of 48

Arrays

Program Using Binary Search (cont)

If (key < a(middle) Then

high = middle – 1

Else

low = middle + 1

End If

End If

Loop

Print “Not found”

Visual Basic Slide 38 of 48

Arrays

Group Exercise

The table below gives names and test scores from a math 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

Richard 135

Geraldine 114

James 92

John 91

Paul 150

Max 114

Robert 91

Barbara 124

Visual Basic Slide 39 of 48

Arrays

Multi-dimensional Arrays

While single dimensional arrays look like this:

A B C D E

A two-dimensional array looks like this:

A1 B1 C1 D1 E1

A2 B2 C2 D2 E2

Visual Basic Slide 40 of 48

Arrays

Declaring a Multi-dimensional Array

0 1 2 3 4 5 6 70

1

2

3

4

5

6

7

If we were to represent a chess board using a multi-dimensional array, we will have the following declaration:

Dim chess(8,8) As Integer

Red square: chess(5,4)

Visual Basic Slide 41 of 48

Arrays

Declaring a Multi-dimensional Array (II)

1

2

3

4

5

6

7

8

Or… to be more specific:

Dim chess(1 To 8, 1 To 8) As Integer

Red square: chess(6,5)

1 2 3 4 5 6 7 8

Visual Basic Slide 42 of 48

ArraysOption explicit‘store values into a two dimensional arrayDim n(1 to 2, 1 to 3) As IntegerPrivate Sub Command1_Click()For i = 1 To 2 For j = 1 To 3 n(i, j) = Val(InputBox(“Enter Num" & “Row” & i & “Col” & j)) Next jNext i‘display contents of the array to listboxFor i = 1 To 2 For j = 1 To 3 List1.AddItem n(i, j) Next jNext iEnd Sub

Multi-Dimensional Array

Visual Basic Slide 43 of 48

Arrays

Exercise

The scores for the top three golfers at the 1999 golf tournament are shown in table below

Round1 2 3 4

Tiger Woods 70 66 65 69Tom Kite 77 69 66 70Tommy 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 Slide 44 of 48

Arrays

SolutionDim nom(1 to 3) as string,score (1 to 3, 1 to 4) as integerPrivate sub command1_click()Dim player, round,total as integerFor player = 1 to 3 nom(player) = inputbox(“enter name”) for round 1 = 1 to 4 nom(player,round) = val(inputbox(“enter score”)) next roundNext player‘compute score for each payerFor player = 1 to 3 let total = 0For round = 1 to 4 let total = total + score(player,round)Next roundPic1.print “The total score for” ; nom(player); “is’’; totalNext player

Visual Basic Slide 45 of 48

Arrays

Control Arrays

• Group together similar function controls

• Min Lower Bound 0 and Max 32767

• Identified by an Integer Index

• ExampleText1(0).text = “Welcome To VB”

Text1(1).text = “Welcome To VB”

Visual Basic Slide 46 of 48

Arrays

Homework

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

Visual Basic Slide 47 of 48

Arrays

Homework

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 Slide 48 of 48

Arrays

Solution

Dim frequency(1 To 10), x, poll As Integer

Private Sub Command1_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

top related