Download presentation
1
Chapter 7 - Visual Basic Schneider
Arrays Chapter 7 - Visual Basic Schneider
2
Chapter 7 - Visual Basic Schneider
Outline and Objective Arrays in Visual Basic One- dimensional arrays Control arrays Searching Sorting Chapter 7 - Visual Basic Schneider
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. Suppose you want to evaluate the exam grades for 30 students.,this means you have to create 30 string variables for names and 30 single vvariables for their scores Array holds either all string values or all numeric values. Chapter 7 - Visual Basic Schneider
4
Chapter 7 - Visual Basic Schneider
Elements 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. The elements of an array are assigned successive memory locations. Chapter 7 - Visual Basic Schneider
5
Chapter 7 - Visual Basic Schneider
Array Declaration Syntax Dim arrayname ( n To m) As VarType Dim grade(1 to 20) as integer Arrayname follows the same rules as variable names. Each array has sufffiient memory reserved to hold the number of items of the given type.. Chapter 7 - Visual Basic Schneider
6
Chapter 7 - Visual Basic Schneider
Variable Arrays A group of variables that have the same name and data type and are related in some way Programmers use arrays to store related data in the internal memory of the computer Data stored inside the computer can be both written and read much faster than data stored in a file on a disk Chapter 7 - Visual Basic Schneider
7
Chapter 7 - Visual Basic Schneider
Variable Arrays 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 array’s name followed by the element’s subscript Chapter 7 - Visual Basic Schneider
8
One-dimensional Array
strState(3) strState(4) strState(5) strState(1) strState(2) Nebraska New Jersey New Mexico Tennessee Texas strState(1) Nebraska strState(2) New Jersey strState(3) New Mexico strState(4) Tennessee strState(5) Texas Chapter 7 - Visual Basic Schneider
9
Chapter 7 - Visual Basic Schneider
Examples of arrays Dim intScore (1 To 30) As integer Dim strStudent (1 To 30 ) As string Dim employee (101 to 350) as string Demo Provinces Chapter 7 - Visual Basic Schneider
10
Initializing an Array by Reading from a File
Dim student ( 1 To 30) As String Open “STUDENTS.TXT” For Input As #1 For count = 1 To 30 Input #1, student ( count ) Next count Close #1 Demo Provinces2 Chapter 7 - Visual Basic Schneider
11
Chapter 7 - Visual Basic Schneider
Parallel Arrays Two arrays are referred to as parallel if subscripted variables having the same subscript (elements) are related. Chapter 7 - Visual Basic Schneider
12
Example of Parallel Arrays
Dim nom ( 1 To 8) As String , score ( 1 To 8 ) As Integer Open “SCORE.TXT” For Input As #1 For student = 1 To 8 Input #1, nom(student), score(student) Next student Close #1 Chapter 7 - Visual Basic Schneider
13
The Average Program Revisited!
Open “STUDENT.TXT” For Input As #1 For count = 1 To 30 Input #1, student (count), score (count) Next count sum = 0 sum = sum + score(count) average = sum/30 Chapter 7 - Visual Basic Schneider
14
Chapter 7 - Visual Basic Schneider
Unknown Array Size What do I do if I don’t know the size of a file – and thus the size of the array?? Chapter 7 - Visual Basic Schneider
15
Chapter 7 - Visual Basic Schneider
Unknown Array Size Dim student() as string Cannot be used without a redim statement Redim student(1 to 37) as string Demo provinces2 Redim preserve student(1 to 38) as string Local vs Form Level Chapter 7 - Visual Basic Schneider
16
Chapter 7 - Visual Basic Schneider
Homework! Go through the seven (7) example programs in section 7.1 of your text book – me – for each program, tell me if you can understand it or not! Chapter 7 - Visual Basic Schneider
17
Chapter 7 - Visual Basic Schneider
Demo Provinces2 Exercises - Schneider Chapter 7 - Visual Basic Schneider
18
Chapter 7 - Visual Basic Schneider
Ordered Array An array is ordered it its values are in either ascending or descending order. For string arrays, the ANSI table is used to evaluate the “less than or equal to” condition. Chapter 7 - Visual Basic Schneider
19
Chapter 7 - Visual Basic Schneider
Ordered Array Ordered strState(3) strState(4) strState(5) strState(1) strState(2) Alabama Kentucky New Mexico Tennessee Virginia strState(3) strState(4) strState(5) strState(1) strState(2) Tennessee Virginia New Mexico Kentucky Alabama Unordered Chapter 7 - Visual Basic Schneider
20
Chapter 7 - Visual Basic Schneider
Ordered Arrays Why order arrays? Chapter 7 - Visual Basic Schneider
21
Chapter 7 - Visual Basic Schneider
Ordered Arrays Efficiency in searching – on average only half a sorted array has to be searched Whole array has to be searched for unordered arrays Chapter 7 - Visual Basic Schneider
22
Chapter 7 - Visual Basic Schneider
Merging A common practice involving arrays is merging two sorted arrays. Chapter 7 - Visual Basic Schneider
23
The method for merging two sorted arrays :
1.Compare the two first elements of the first and second arrays. A. If one name alphabetically precedes the other, copy it onto the third list and cross it off the original array. B. If the names are the same, copy the name onto the third list and cross out the name from both arrays. 2. Repeat Step 1 with the new name in the array until you reach the end of either array. 3. Copy the names from the remaining array onto the third array. Demo Merge Chapter 7 - Visual Basic Schneider
24
Chapter 7 - Visual Basic Schneider
Passing an Array An array can be passed to another procedure by reference. Dim scores(1 to 10) as integer Call sort(scores( )) Chapter 7 - Visual Basic Schneider
25
Example of Passing an array:
Private Sub cmddisplay_Click() ' Pass array to subprogram and function Dim score(1 To 5) As Integer Call FillArray(score( ) ) picAverage.Cls picAverage.Print ”Average is"; Sum(score( ) ) / 5 End Sub Passing array score This array is not dimensioned in the declaration section of General , so is local to this procedure and unknown to other procedures. Chapter 7 - Visual Basic Schneider
26
Array Score is passed to a Subprogram
Private Sub FillArray(s( ) As Integer) ' Fill array with scores s(1) = 85 s(2) = 92 s(3) = 75 s(4) = 68 s(5) = 84 End Sub This array is pointing to the same location as array score Total = 404 404/5 =80.8 Chapter 7 - Visual Basic Schneider
27
Array Score is passed to a Function
Private Function Sum(s ( ) As Integer) As Integer Dim total As Integer, index As Integer ' Add up scores total = 0 For i = 1 To 5 total = total + s(i) Next i Sum = total End Function Chapter 7 - Visual Basic Schneider
28
Exercises - Schneider 332 - 337
Chapter 7 - Visual Basic Schneider
29
Chapter 7 - Visual Basic Schneider
Control Arrays Chapter 7 - Visual Basic Schneider
30
Chapter 7 - Visual Basic Schneider
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. To create additional elements of the txtBox() Control array during form design, make the control active,press CRTL +C . VB has recorded all the properties associated with textbox(00) . To creat a copy press CTRL + V The value of the index for the new textbox(1) is 1; Note all the properties of textbox are being passed to other textboxes. Chapter 7 - Visual Basic Schneider
31
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 Demo Chapter 7 - Visual Basic Schneider
32
Chapter 7 - Visual Basic Schneider
Review Provinces2 Demo ColourArray Chapter 7 - Visual Basic Schneider
33
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 Index property for the elements of the control array must be passed. Example: Private Sub txtBox_GotFocus (Index As Integer) In chapter 3 we discussed several events related to text boxes. One example was GotFocus event procedure. An ordinary txtBox wold be Private Sub txtBox_GotFocus( ) But for txtBox a control array the GotFocus begins with Private Sub ttxtBox_GotFocus (Index As Integer) Chapter 7 - Visual Basic Schneider
34
Control Array Event Procedures:
Demo Elements Demo GradeArray Demo CalculatorwithArray Chapter 7 - Visual Basic Schneider
35
Creating Control Array at Run Time:
You can create elements of a control array via a Load statement at run time. Demo Load Copying and positioning control array elements can become tedious if the number of elements is large. Also the actual number of elements needed in a control array may not be known until a response from the user is processed at run time. They are 1440 wip to the inch. You want the new element has its unique location on the form.. Chapter 7 - Visual Basic Schneider
36
Chapter 7 - Visual Basic Schneider
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. Chapter 7 - Visual Basic Schneider
37
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. Demo Tax Before discussing creating arrays at run time, yu must consider- the Left, Top, Width, and Height properties of controls. They are 1440 Twips to the inch. When a control ic active, the two panels on the right side of the toolbar give the location and size of the control , respectively.. The location and size properties of a control array ca be altered at run time with statement t such as : Text1.Left = 480 Text2.Top = Text1.Top * Text1.Height ( which places Text2 a comfortable distance below Text1. Chapter 7 - Visual Basic Schneider
38
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) blMonth(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 i End Sub
39
Chapter 7 - Visual Basic Schneider
Schneider p Chapter 7 - Visual Basic Schneider
40
Chapter 7 - Visual Basic Schneider
Processing Arrays Searching successive elements of an array is called Sequential 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. Chapter 7 - Visual Basic Schneider
41
Example of Sequential Search (finding the quiz grades greater than 8)
Dim quiz ( 1 To 15) As Single For position =1 TO 15 If quiz(position) > 8 THEN picOutput.Print quiz (position) count = count + 1 End If Next Position The variable count keeps track of Chapter 7 - Visual Basic Schneider
42
Chapter 7 - Visual Basic Schneider
Sequential Search Useful for short lists. Very inefficient for long lists ( example names in telephone book). Use binary search if the list is sorted. Chapter 7 - Visual Basic Schneider
43
Chapter 7 - Visual Basic Schneider
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. Chapter 7 - Visual Basic Schneider
44
Chapter 7 - Visual Basic Schneider
Binary Search Private Sub BinarySearch(corp As String, result As String foundFlag = '1 indicates corp found first = 1 last = numFirms Do While (first <= last) And (foundFlag = 0) middle = Int((first + last) / 2) Select Case UCase(firm(middle)) Case corp foundFlag = Case Is > corp last = middle Case Is < corp first = middle End Select Loop End Sub Chapter 7 - Visual Basic Schneider
45
Chapter 7 - Visual Basic Schneider
Binary Search If foundFlag = 1 Then result = "found” Else result = "not found End If Chapter 7 - Visual Basic Schneider
46
Chapter 7 - Visual Basic Schneider
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. Ascending : lowest to highest descending: highest to lowest When characters are compared the computer uses the ASCII value of each character to compare if the letter A is less than the letter B Chapter 7 - Visual Basic Schneider
47
Chapter 7 - Visual Basic Schneider
Types of Sorting Bubble Sort Shell Sort Chapter 7 - Visual Basic Schneider
48
Chapter 7 - Visual Basic Schneider
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. Notice that the Flag is set to 1 before the loop is entered . Its value is later checked to determine if the entire array is in order. The Final is set to one less than the number of items to be sorted. This is because two items at a time are compared . And you do not want to go over the boundary of the array Examine the block IF statement in the FOR… NEXT loop . This statement determines whether two adjacent element should beexchanged. The following program segment demonstrate SWAP X = 20 Y = 10 SWAP X, Y We need a DO WHILE… LOOP to sort the whole list. As long as FLAG =1 Basic knows switches have been made When the loop is completed without setting the Flag = 1 - that is when no switches are made Chapter 7 - Visual Basic Schneider
49
Chapter 7 - Visual Basic Schneider
Bubble Sort For passNum = 1 To 4 'Number of passes is 1 less than number of items For index = 1 To 5 - passNum If name(index) > name(index + 1) Then Call SwapData( name( ), index) End If Next index Next passNum Chapter 7 - Visual Basic Schneider
50
Swapping two variables
Private Sub SwapData ( A ( ) As String, index As Integer) Dim temp As String temp = A ( index) A(index ) = A (index + 1) A ( index + 1) = temp End Sub Chapter 7 - Visual Basic Schneider
51
Chapter 7 - Visual Basic Schneider
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. Chapter 7 - Visual Basic Schneider
52
Chapter 7 - Visual Basic Schneider
Shell Sort Is similar to the bubble sort, but instead of comparing and swapping adjacent elements A(count) and A(count+1), it compares and swaps nonadjacent elements A(count) and A(count + Gap) , where Gap starts considerably greater than 1. Gap is equal to one-half the size of the list. The elements of the list are separated by the chosen gap and grouped into subsists. Is more efficient for longer lists (100 or more elements) Is a good compromise between speed and simplicity. The shell sort was named for its inventor, Donald Shell, is much more efficient for really long lists For very short list s, the bubble sort is preferable; however for a lis of 30 items or more, the shell sort will consistently outperform the bubble sort. Chapter 7 - Visual Basic Schneider
53
Chapter 7 - Visual Basic Schneider
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. Begin with a gap of g =Int(n/2) compare items 1 and 1+g , 2 and 2 + g,….. N-g and n. 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, 4 until tahe value of gap is 0. Chapter 7 - Visual Basic Schneider
54
Chapter 7 - Visual Basic Schneider
Shell Sort gap = Int(numParts / 2) Do While gap >= 1 Do doneFlag = 1 For index = 1 To numParts - gap If part(index) > part(index + gap) Then Call Swap( part(index), part(index + gap) doneFlag = 0 End If Next index Loop Until doneFlag = 1 gap = Int(gap / 2) 'Halve the length of the gap Loop For lists of 3elements or more, the shell sort will consistently outperform outperform the bubble sort. Chapter 7 - Visual Basic Schneider
55
Efficiency of Bubble and Shell sort
Array Elements Bubble Sort Shell Sort , ,517 Chapter 7 - Visual Basic Schneider
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.