Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

51
Chapter 7 - Visual Basic Schneider 1 Chapter 7 Arrays
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    276
  • download

    16

Transcript of Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

Page 1: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

Chapter 7 - Visual Basic Schneider 1

Chapter 7

Arrays

Page 2: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

2

Outline and Objective Arrays in Visual Basic

One- dimensional arrays Control arrays Two-dimensional arrays

Searching Sorting

Page 3: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

3

Array verses Simple Variable Simple variable is used to store a single

value. Array variable is used to represent many

values of the same type with one variable name.

Page 4: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

4

Parts of an Array Array Name: A valid variable name for the

structure. Subscript or Index : A value that refers to a

particular array element. Which must be defined as an integer

Element: An individual data item within an array.

Page 5: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

5

Array Declaration Syntax

Dim arrayname ( 1 To n) As VarType

Page 6: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

6

Examples of arrays Dim strMonth ( 1 To 12) As String Dim intScore (1 To 30) As Integer Dim strStudents (1 To 30 ) As String Dim strStudents (30) as String

Will the last two arrays hold the same number of elements?

Page 7: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

7

The Dim Statement Used when you need to define an array . The Dim statement sets up storage area in

memory for the array. ******A Dim statement must occur

before the first reference to the array elements.*******

Page 8: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

8

Initializing an ArrayPrivate Sub cmdWhoWon_Click() Dim strTeamName( 1To 5) As String Dim n As Integer ' Fill array with World Series Winners strTeamName(1) = "Red Sox" strTeamName(2) = "Giants" strTeamName(3) = "White Sox" strTeamName(4) = "Cubs" strTeamName(5) = "Cubs" n = Val(txtNumber.Text) picWinner.Print "The "; strTeamName(n); " won World

Series number"; nEnd Sub

Page 9: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

9

Array strTeamName()

strTeamName( 1 To 5) As String

Red Sox Giants White Sox Cubs Cubs

strTeamName(1)

Array Name

Index

Page 10: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

10

Initializing an Array by Reading from a File

Dim strCereal ( 1 To 30) As String

Dim strMfr (1 to 30) as string

Dim intCount as Integer

Open “Cereal.txt” For Input As #1

For intCount = 1 To 70

Input #1, strCereal ( intCount ), strMfr(intcount)

Next intCount

Page 11: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

11

Parallel Arrays, Use the same indexDim intScore( 1 To 30) As Single, strStudent (1 To 30) As

String

Dim sngAverage as Single , intSum as Integer

Open “StudentFile.txt” For Input As #1

intSum = 0

For intCount = 1 To 30

Input #1, strStudent (intCount), intScore (intCount)

intSum = intSum + intScore(intCount)

Next intCount

sngAverage = sum/30

Page 12: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

12

Parallel Arrays

Arrays are parallel if subscripted variables have the same subscript and are related.

Page 13: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

13

Example of Parallel Arrays

Dim strName ( 1 To 8) As String

Dim intScore ( 1 To 8 ) As Integer

Dim intStudent as Integer

Open “Score.txt” For Input As #1

For intStudent = 1 To 8

Input #1, strName(intStudent), intScore(intStudent)

Next intStudent

Close #1 intStudent is the ?

Page 14: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

14

Summing the Elements of an Array in a For-Next Loop

12345

RateOfReturnFor K = 1 To 5Sum = Sum + RateOfReturn(K)Next K

When K = 1,the statement isSum = Sum + RateOfReturn(1)

Page 15: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

15

Ordered Array

An array is ordered if its values are in either ascending or descending order.

For string arrays, the ASCI table is used to evaluate the “less than or equal to” condition. Is “Ace” > “Nine”

Page 16: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

16

Processing Arrays Searching successive elements of an array

is called a Sequential Search. Also called linear search or serial search.

A Sequential Search examines each element , from the first to the last, until the specified value is found or the end of the array is reached.

Page 17: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

17

Example of Sequential Search (finding the sngQuiz grades greater than 8)

Dim sngQuiz ( 1 To 15) As Single

Dim intPosition as Integer

For intPosition =1 TO 15

If sngQuiz(intPosition) > 8 THEN

picOutput.Print sngQuiz (intPosition)

intCount = intCount + 1

End If

Next intPosition

picOutput.Print “Number of Grades found =“ intCount

Page 18: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

18

Sequential Search

Useful for short lists. 1 to 500 elements Very inefficient for long lists ( example

names in telephone book). Use binary search if the list is sorted.

Page 19: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

19

Binary Search In binary search, an ordered array is

repeatedly divided in half. The half not containing the target value is ignored.

To use binary search, the data in the array must be arranged in ascending or descending order. (Sorted)

Page 20: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

20

1

2

3

4

5

6

7

8

9

10

11

Binary search with a target

value of 76

SampleArrayLowerbound

Upperbound

Begin search at midpoint of array (element 6)

mid = (lowerbound + upperbound) \ 2

If value in element 6 is = 76, then we are done.

If value in element 6 is < 76, then set lower bound to mid + 1.

Otherwise, set upper bound to mid - 1.

Page 21: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

21

Now recompute the midpoint

mid = (lowerbound + upperbound) \ 2

If value in element 9 is = 76, then we are done.If value in element 9 is < 76, then set lower

bound to mid + 1.Otherwise, set upper bound to mid - 1.

SampleArray

Lowerbound

Upperbound

Binary search with a target

value of 761

2

3

4

5

6

7

8

9

10

11

Page 22: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

22

1

2

3

4

5

6

7

8

9

10

11

Now recompute the midpoint

mid = (lowerbound + upperbound) \ 2Recall that the arithmetic operator (\) means integer division (15 \ 2 = 7)

SampleArray

Lowerbound

Upperbound

Binary search with a target

value of 76

We have now found the value we were searching for. If we had not found the value, we would have adjusted the lower or upper bound as appropriate and then computed a new midpoint.

Page 23: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

23

Dim strFirm(1 to 100) as StringPrivate Sub BinarySearch(strCorp As String, strResult As String)Dim first as Integer, middle as Integer, last as IntegerDim Found as Integer, intFirms as Integer, strFirm as String Found = 0 '1 indicates strCorp has been found first = 1; last = intFirms

Do While (first <= last) And (foundFlag = 0) middle = Int((first + last) / 2) Select Case UCase(strFirm(middle)) Case strCorp Found = 1 Case Is > strCorp last = middle - 1 Case Is < strCorp first = middle + 1 End Select

LoopEnd Sub

Page 24: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

24

Passing an Array

An array can be passed to another procedure by Reference.

Page 25: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

25

Example of Passing an array:Private Sub cmddisplay_Click()

' Pass array to Sub Procedure and function

Dim intScore(1 To 5) As Integer

Call FillArray(intScore( ) )

picAverage.Cls

picAverage.Print ”Average is"; Sum(intScore( ) ) / 5

End Sub

Passing array intScore

User Function

Page 26: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

26

Array intScore is passed to a Subprogram

Private Sub FillArray(s( ) As Integer) ' Fill array with intScores s(1) = 85 s(2) = 92 s(3) = 75 s(4) = 68 s(5) = 84End Sub

This array is pointing to the same location as array intScore

Page 27: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

27

Array intScore is passed to a Function

Private Function Sum(s ( ) As Integer) As Integer

Dim intTotal As Integer, intIndex As Integer

' Add up intScores

intTotal = 0

For intIndex = 1 To 5

intTotal = intTotal + s(intIndex)

Next intIndex

Sum = intTotal

End Function

Page 28: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

28

Control Array A means of constructing arrays of text

boxes, labels, and command buttons. At least one element of a control array

must be created when the form is designed.

The remaining elements can be created either during form design, or with the Load statement.

Page 29: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

29

Creating Control Array during Form Design

Add one instance of the desired control to the form

Set the Index property to a number Set any other properties that will be

common to all other elements Click on the control and then press Ctrl+C Press Ctrl + V, to create the next element

Page 30: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

30

Control Array All the properties of the first element are

passed to other elements of the control array including the Top and Left properties.

The only property that differs from first element is the Visible property.

The Load statement sets the Visible property to False.

Page 31: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

31

Control Array Event Procedures:

Even though we may have many elements in the txtBox( ) control array, we will have just one txtBox_GotFocus event procedure to deal with.

The value of intIndex property for the elements of the control array must be passed.

Example:

Private Sub txtBox_GotFocus (intIndex As Integer)

Page 32: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

32

Creating Control Array at Run Time:

You can create elements of a control array by using the Load statement at run time.

Page 33: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

33

Creating Control Array at Run Time: The standard unit of measurement is called

Twip. To place a new element of a control array,

adjust the Top and Left properties during run time.

Set the Visible property to True.

Page 34: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

34

The location and size of a control

Set the index property to zero!

Page 35: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

35

Example ( Creating control array during run time)

Private Sub Form_Load() Dim i As Integer, monthNames As String monthNames = "FebMarAprMayJunJulAugSepOctNovDec" For i = 1 To 11

Load lblMonth(i)

Load txtInfo(i) lblMonth(i).Top = lblMonth(i - 1).Top + txtInfo(0).Height txtInfo(i).Top = txtInfo(i - 1).Top + txtInfo(0).Height lblMonth(i).Caption = Mid(monthNames, 3 * i - 2, 3) lblMonth(i).Visible = True txtInfo(i).Visible = True

Next iEnd Sub

Page 36: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

36

Sorting A common practice involving arrays is

sorting the elements of the array in either ascending or descending order.

You can sort an array in alphabetic order or numeric order.

There are various methods to sort data items.

Page 37: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

37

Types of Sorting Bubble Sort Shell Sort

Page 38: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

38

Bubble Sort The bubble sort involves comparing

adjacent elements and swapping the values of those elements when they are out of order.

One complete time through the array is called a pass.

Page 39: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

39

Bubble SortFor passNum = 1 To 4 'Number of passes is 1 less than

number of items

For intIndex = 1 To 5 - passNum

If name(intIndex) > name(intIndex + 1) Then

Call SwapData( name( ), intIndex)

End If

Next intIndex

Next passNum

Page 40: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

40

Swapping two variablesPrivate Sub SwapData ( A ( ) As String, intIndex As

Integer)

Dim temp As String

temp = A ( intIndex)

A(intIndex ) = A (intIndex + 1)

A ( intIndex + 1) = temp

End Sub

Page 41: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

41

Bubble Sort The maximum number of passes necessary to sort

the elements in an array is equal to the number of elements in the array less 1.

The minimum number of passes to sort an array may be one.

It works well for a small number of data items. It is too slow for really long lists.

Page 42: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

42

Shell Sort Is similar to the bubble sort, but instead of

comparing and swapping adjacent elements A(intCount) and A(intCount+1), it compares and swaps nonadjacent elements A(intCount) and A(intCount + Gap) , where Gap starts considerably greater than 1.

Page 43: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

43

Shell Sort Gap is set to one-half the length of the array. After each pass if flag is set to 1, then Gap is

halved again for the next pass. At the end Gap becomes one, and adjacent

elements are compared and swapped.

Page 44: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

44

Shell Sort gap = Int(numParts / 2) Do While gap >= 1 Do doneFlag = 1 For intIndex = 1 To numParts - gap If part(intIndex) > part(intIndex + gap) Then Call Swap( part(intIndex), part(intIndex + gap)

doneFlag = 0 End If Next intIndex Loop Until doneFlag = 1 gap = Int(gap / 2) 'Halve the length of the gap Loop

Page 45: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

45

Efficiency of Bubble and Shell sort

Array Elements Bubble Sort Shell Sort

5 10 1515 105 115

25 300 302

30 435 364

100 4950 2638

500 124,75022,517

Page 46: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

46

Two-Dimensional Arrays Store values as a table, grouped into rows

and columns. The first subscript of a two-dimensional

array refers to the row and the second subscript to the column.

Page 47: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

47

Declaration of Two-Dimensional Array Syntax:

Dim arrayname (r1 To n1, c2 To n2) As vartype

Example: Dim rm (1 To 4, 1 To 4) As Single

column

row

Page 48: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

48

Example of a two-dimensional array:

rm(1 To 4, 1 To 4)

0 2054 802 738 2054 0 2786 2706 802 2786 0 100 736 2706 100 0

Chicago

Los AngelesNew York

Philadelphia

Chicago Los Angeles New York Philadelphia

rm (2,2)rm (3,4)

Page 49: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

49

Example of Input File0, 2054, 802, 738

2054, 0, 2786, 2706

802, 2786, 0, 100

738, 2706, 100, 0

Page 50: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

50

Manipulating a Two-Dimensional Array

Use nested For ….. Next loops to assign or access elements of a two-dimensional array.

Example: For row = 1 To 4

For col = 1 To 4

Input #1, rm(row, col)

Next col

Next row

Page 51: Chapter 7 - Visual Basic Schneider1 Chapter 7 Arrays.

51

Example of two-dimensional arrayDim a(1 To 4, 1 To 5 ) As Integer

Private Sub cmdDisplay_Click()

For j = 1 To 4

For k = 1 To 5

a (j, k) = (j - k) * j

picOutput.Print a(j,k);

Next k

picOutput.Print

Next j

End Sub