Presentation is loading. Please wait.

Presentation is loading. Please wait.

ARRAYS Variable Arrays, Control Arrays, Dynamic Variable Arrays, Dynamic Control arrays.

Similar presentations


Presentation on theme: "ARRAYS Variable Arrays, Control Arrays, Dynamic Variable Arrays, Dynamic Control arrays."— Presentation transcript:

1 ARRAYS Variable Arrays, Control Arrays, Dynamic Variable Arrays, Dynamic Control arrays

2 Scope Local or Procedure-level: variable is available only within the subroutine or function in which it is declared Global or Module-level: variable is available to all subroutines within a module, e.g. all the subroutines associated with a form Friend: variable is available to other forms within a project, but is not available to anyone outside the project Public: variable is available to other projects

3 Multi-Form Demo A Public variable on first form is available to use on the second form.

4 Form 1 Code Public sFirstName As String
Private Sub cmdShowForm2_Click() sFirstName = txtForm1.Text txtForm1.Text =“” ‘no longer in TextBox frmForm2.Show frmForm1.Hide End Sub

5 Form 2 Code Private Sub cmdReturn_Click() frmForm2.Hide frmForm1.Show
End Sub Private Sub Form_Activate() txtForm2.Text = frmForm1.sFirstName

6 Variable Arrays If a group of variables are
of the same type (e.g. all Integer) Note: same type does not mean same value. and play a similar role (i.e. the code for them is nearly identical) it is convenient to make them an array For example, grade1, grade2, … becomes grade(0), grade(1), …. Chapter 7 in Schneider

7 Arrays in Memory Recall variables correspond to memory locations.
The elements of an array are stored in consecutive memory locations. When you refer to the entire array, you “point” to the first memory location.

8 Before and After Arrays
Dim iGrade1 As Integer Dim iGrade2 As Integer Dim iGrade3 As Integer Dim iGrade4 As Integer Dim iGrade5 As Integer Dim iGrade6 As Integer BECOMES Dim iGrade(5) As Integer ‘zero-based

9 Before and After Arrays
dAverage = (iGrade1 + iGrade2 + iGrade3 + _ iGrade4 + iGrade5 + iGrade6) / 6 BECOMES dAverage = 0 For i = 0 To 5 dAverage = dAverage + iGrade(i) Next i dAverage = dAverage / 6

10 Array Vocabulary Array: refers to the entire set of related variables.
Element: refers to one member of the array. Index: (a.k.a. subscript) is an integer (0,1,2,…) that is used to identify an individual member within the set. iGrade is the array, iGrade(3) is an element in that array, that element has an index 3 (note: it is the fourth item)

11 More Array Vocabulary Option Base:
If you declare iGrade(5), VB makes an array with six elements iGrade(0) through iGrade(5), that is, it starts indexing at 0. If you want to start indexing at 1, you can type Option Base 1 (just below Option Explicit). Note: Control Arrays are always zero based (regardless of Option Base).

12 Average, High and Low Locked TextBoxes

13 Average, High and Low Input Box

14 Average, High and Low

15 Average, High and Low Option Explicit Const SCORENUMBER As Integer = 5
Private Sub cmdEnter_Click() Dim iScore(SCORENUMBER - 1) As Integer Dim i As Integer Dim iSum As Integer Dim iMin As Integer Dim iMax As Integer Dim dAverage As Double

16 Average, High and Low iScore(0) = InputBox("Enter Score 1: ")
iSum = iScore(0) iMin = iScore(0) iMax = iScore(0) ‘Enter first score outside of loop and make it the ‘min and the max

17 Average, High and Low For i = 1 To SCORENUMBER - 1
iScore(i) = InputBox("Enter Score " & i + 1 & ": ") iSum = iSum + iScore(i) If iScore(i) < iMin Then iMin = iScore(i) End If If iScore(i) > iMax Then iMax = iScore(i) Next i

18 Average, High and Low dAverage = Sum / SCORENUMBER
txtAverage.Text = dAverage txtHigh.Text = iMax txtLow.Text = iMin End Sub Private Sub Form_Load() lblInstruct.Caption = "Click the button below to begin " & _ "entering the " & SCORENUMBER & " scores and “ & _ “calculate " & “their average, high and low." ‘The use of SCORENUMBER makes the program scale.

19 Scaling To scale something is to change its size (e.g. changing the number of elements in an array). If a program is written in a way which facilitates various size changes, it is said to be “scalable.” The use of the constant SCORENUMBER in the previous code made it scalable, since the code would need only one change if the size of the score array were varied.

20 Array as argument of a Function: #1
Const NUMBEROFGRADES As Integer = 5 Private Sub cmdEnter_Click() Dim iGrade(NUMBEROFGRADES -1) As Integer Dim dAve As Double Dim i As Integer For i = 0 To NUMBEROFGRADES - 1 iGrade(i) = InputBox("Enter Grade " & i+1, _ "Grades") Next i dAve = dAverage(iGrade) txtAverage.Text = dAve End Sub ‘No parentheses in the function call.

21 Array as argument of a Function: #2
Private Function dAverage(iArray() As Integer) As Double Dim i As Integer dAverage = 0.0 For i = LBound(iArray) To UBound(iArray) dAverage = dAverage + iArray(i) Next i dAverage = dAverage / (UBound(iArray) - _ LBound(iArray) + 1) End Function ‘Parentheses in the function definition.

22 Array Bounds The Lower Bound is the lowest index in an array (can be negative). Index not value. The Upper Bound is the highest index in an array (can be negative). LBound(ArrayName) returns the lower bound of a variable array. UBound(ArrayName) returns the upper bound of an variable array.

23 Randomly shuffling an array of strings
Private Sub Shuffle(sArray() As String) ‘Strings only Dim i As Integer Dim j As Integer Dim Swap As String ‘temporary string for swapping Dim iLb as Integer iLb = LBound(sArray) ‘lower bound of array dim iUb as Integer iUb = UBound(sArray) ‘upper bound of array For i = iLb To iUb j = iLb + Int( (iUb - iLb + 1) * Rnd() ) Swap = sArray(i) sArray(i) = sArray(j) sArray(j) = Swap Next i End Sub

24 By Reference In VB the default situation is that variables are passed to a function “by reference” (whether or not they are arrays). That is, if the variable is changed in the function, it is also changed in the caller.

25 Control array If a group of controls are
of the same type (e.g. all CommandButtons) and play a similar role (i.e. the code for them is nearly identical), it is convenient to make them an array Section 7.3 in Schneider (p. 338)

26 Pasting a TextBox Clicking Yes to the create a Control Array questions assigns a 0 to the original TextBox’s Index property and a 1 to the new TextBox’s Index property.

27 Array of TextBoxes

28 Code for Array of Textboxes
Option Explicit Private Sub cmdSumHours_Click() Dim i As Integer 'Counter Dim iTotal As Integer iTotal = 0 For i = 0 To txtHours.Ubound iTotal = iTotal + txtHours(i).Text Next i txtSum.Text = iTotal End Sub ‘For a control array Ubound is a property NOT function

29 Which button was pressed?

30 Which button (code) Option Explicit Dim iButtonIndex As Integer
Private Sub cmdButton_Click(Index As Integer) iButtonIndex = Index End Sub Private Sub cmdWhich_Click() txtWhich.Text = cmdButton(iButtonIndex).Caption & _ " was last pressed." Comes automatically and tells us which button was pressed

31 Collection of Forms The index property comes into play when a control is an element in an array Notice that forms do not have an index property However there is a way to apply scaling ideas to forms Forms have an order, the order in which they are loaded The third form loaded can be referred to as Forms(2) (zero-based counting) Name property not needed

32 Toward Scaling with Forms

33 Option Explicit Dim iFormIndex As Integer Private Sub optForm_Click(Index As Integer) iFormIndex = Index + 1 End Sub Private Sub cmdGoToForm_Click() Me.Hide Forms(iFormIndex).Show 'the order in which forms are loaded is their order in the collection Private Sub Form_Load() Call Load(frmNumber1) Call Load(frmNumber2) Load frmNumber ‘note alternate syntax for calling subs

34 LISTBOXES

35 Font Selection ListBox

36 Font Selection ListBox

37 Font Selection ListBox

38 Font Selection ListBox

39 Font Selection ListBox
Option Explicit Private Sub lstFont_Click() txtMessage.FontName = lstFont.Text End Sub Private Sub cmdAddFont_Click() lstFont.AddItem (txtNewFont.Text) txtNewFont.Text = "" Has a click event Text of the currently highlighted item Method to add an item to the list

40 Font Selection ListBox
Private Sub Form_Load() Dim i As Integer Const PHRASE As String = "All work and no ” & _ “play makes Jack a dull boy." & vbCrLf For i = 1 To 20 txtMessage.Text = txtMessage.Text + PHRASE Next i End Sub

41 Choose a Team ListBox Set listbox’s MultiSelect property to 1 in design time.

42 Choose a Team ListBox

43 Choose a Team ListBox

44 Choose a Team ListBox Option Explicit Private Sub cmdAddName_Click()
lstNames.AddItem (txtName.Text) txtName.Text = "" End Sub

45 Choose a Team ListBox Private Sub cmdChooseTeam_Click()
Dim i As Integer For i = 0 To lstNames.ListCount - 1 If lstNames.Selected(i) Then lblTeam.Caption = lblTeam.Caption & _ lstNames.List(i) & " " End If Next i cmdChooseTeam.Enabled = False End Sub The number of items currently in a listbox An array of booleans, true if the item is selected, false otherwise An array containing the text for each item

46 Choose a Team ListBox Private Sub Form_Load()
lstNames.AddItem ("Lucy") lstNames.AddItem ("Ricky") lstNames.AddItem ("Fred") lstNames.AddItem ("Ethel") End Sub

47 Properties of a ListBox
The List() property of the ListBox is an array of strings corresponding to what is written for each item in the list. The Selected() property is an array of booleans to indicate which items are selected (useful when the MultiSelect property is 1 or 2). If MultiSelect is set to 0 (None) it is easier to use the Text (for the currently selected text) and ListIndex (for the currently selected index) properties.

48 Properties of a ListBox
The ItemData() property is an array of Longs (integers) which is not displayed, it allows the programmer to associate an additional piece of data to each item in the list. The AddItem method allows one to add items to the list; this means that the associated arrays List(), Selected() and ItemData() are variable in size — they are dynamic arrays

49 DYNAMIC ARRAYS

50 Dynamic Array When the size (the number of elements) of an array is not known until runtime, a dynamic array is required. When declaring the array (Dim), the dynamic array has empty parentheses. When the array size is known, use the keyword ReDim to establish the size of the array.

51 Unknown number of grades

52 Unknown Number of Grades (Code)
Option Explicit Dim iGrades() As Integer Dim iNumberGrades As Integer Private Sub cmdEnter_Click() iNumberGrades = txtGradeNumber.Text - 1 ReDim iGrades(iNumberGrades) Dim dAve As Double Dim i As Integer For i = LBound(iGrades) To UBound(iGrades) iGrades(i) = InputBox("Enter Grade " & i, "Grades") Next i dAve = dAverage(iGrades) ‘Average function given before txtAverage.Text = dAve End Sub Don’t know size when declaring Now we know the size

53 DYNAMIC CONTROL ARRAYS

54 Dynamic Control Arrays
If there is unknown number of controls at design time, one needs a dynamic control array. One drags and drops the first one onto the form, gives it an index of 0, and then adds others when the desired number of controls is known. The problem with the dynamic control arrays is that they must be placed on the form, but where?

55 Top and Left The Top and Left properties determine the position of a control within its container, which may be a Form, a Frame or a PictureBox.

56 Coordinate System Top is typically measured from the top of the container down to top of the control. Left is typically measured from the left of the container over to the left of the control. Top Left

57 Moving Button Click the button and it moves a random amount.

58 Moving Button

59 Moving Button (Code) Option Explicit Const MOVEAMOUNT AS Integer =1000
Private Sub cmdMove_Click() cmdMove.Top = cmdMove.Top + MOVEAMOUNT _ * (1 - 2 * Rnd()) cmdMove.Left = cmdMove.Left + MOVEAMOUNT _ * (1 - 2 * Rnd()) If cmdMove.Left < 0 Then cmdMove.Left = 0 End If End Sub

60 What a stwange twip it’s been
Twip is the usual unit used for measuring sizes in VB forms and controls. Another unit of size is the point. Fonts are typically measured in Points. There are 72 Points to an inch. The default is 20 twips per point (or 1440 twips per inch).

61 Dynamic Control Array Generates a number of textboxes and labels determined at runtime.

62 Dynamic Control Array Code (Part 1)
Don’t know how many grades Option Explicit Dim iGrades() As Integer Dim iNumberGrades As Integer Const SPACING As Integer = 100 Private Sub cmdOK_Click() iNumberGrades = txtGradeNumber.Text ReDim iGrades(iNumberGrades - 1) Dim iHeight As Integer Dim i As Integer Now we know

63 Dynamic Control Array Code Part 2
iHeight = lblStudent(0).Height + SPACING For i = 1 To iNumberGrades - 1 Load lblStudent(i) Load txtGrade(i) lblStudent(i).Top = lblStudent(i - 1).Top + iHeight txtGrade(i).Top = txtGrade(i - 1).Top + iHeight lblStudent(i).Visible = True txtGrade(i).Visible = True lblStudent(i).Caption = "Student" & i + 1 Next i txtGrade(0).SetFocus End Sub Introduces a new label and textbox onto the form Assigns Top of new control so that it is under previous control New controls are made invisible by default, you must make them visible if you want to see them

64 Dynamic Control Arrays
The first control in the array is placed on the form and given an index of 0 When an element of a control array is loaded, it is given the same Top and Left properties as the original (same Height and Width too) A more reasonable Top and Left must be provided, else the controls are superimposed if you only see one control you either forgot to change left or top OR you did not make it visible.

65 Dynamic Control Arrays
The newly loaded control has its Visible property set to False, so they must be made visible If the program allows the size of the control array to be altered, then one might have to unload some of the controls Unload them in reverse order For i= lastcontrolnumber To 1 Step -1

66 Unloading

67 Unloading (Code) Private Sub cmdClear_Click() Dim i As Integer
For i = iNumberGrades - 1 To 1 Step -1 Unload lblStudent(i) Unload txtGrade(i) Next i txtGradeNumber.Text = "" txtGradeNumber.SetFocus txtGrade(0).Text = "" End Sub Not 0 Backwards! Getting rid of a control

68 Toward Rows and Columns: Integer Division
There are two ways to divide integers in VB The first way results in a float (real number) 15 / 4  3.75 The second way results in an integer (the whole number part of the above result) 15 \ 4  3 Note VB uses a backward slash to indicate integer division

69 Toward Rows and Columns: Mod
Another outcome of integer division is the modulus (or remainder) 15 Mod 4  3 Useful if you have players taking turns Player = (Player + 1) Mod NumberOfPlayers If Number Mod 2 = 0 Then “even” Else “odd”

70 Rows and Columns Control arrays are one dimensional arrays, i.e. there is only one index Integer division and modulus can help one make a one-dimensional array look like a two-dimensional array Internally multi-dimensional arrays are really single dim

71 Three Rows 1 2 3 Index: 0 R: 0 Mod 3 C: 0 \ 3 Index: 3 R: 3 Mod 3
1 2 3 Index: 0 R: 0 Mod 3 C: 0 \ 3 Index: 3 R: 3 Mod 3 C: 3 \ 3 Index: 6 R: 6 Mod 3 C: 6 \ 3 Index: 9 R: 9 Mod 3 C: 9 \ 3 Index: 1 R: 1 Mod 3 C: 1 \ 3 Index: 4 R: 4 Mod 3 C: 4 \ 3 Index: 7 R: 7 Mod 3 C: 7 \ 3 Index: 10 R: 10 Mod 3 C: 10 \ 3 Index: 2 R: 2 Mod 3 C: 2 \ 3 Index: 5 R: 5 Mod 3 C: 5 \ 3 Index: 8 R: 8 Mod 3 C: 8 \ 3 Index: 11 R: 11 Mod 3 C: 11 \ 3

72 Controls in Rows and Columns
A control’s Left property is determined by what column it is in, which is related to Index \ RowNumber or Index Mod ColumnNumber A control’s Top property is determined by what row it is in, which is related to Index Mod RowNumber or Index \ ColumnNumber

73 Marilyn and Andy

74 Marilyn and Andy

75 Marilyn and Andy Private Sub cmdMakePanel_Click()
Dim iRow As Integer, iCol As Integer Dim i As Integer Dim iHeight As Integer, iWidth As Integer iRow = txtRow.Text iCol = txtCol.Text iHeight = picMarilyn(0).Height iWidth = picMarilyn(0).Width

76 Marilyn and Andy For i = 1 To iRow * Col - 1 Load picMarilyn(i)
picMarilyn(i).Top = picMarilyn(0).Top +_ (i Mod iRow) * iHeight picMarilyn(i).Left = picMarilyn(0).Left + _ (i \ iRow) * iWidth picMarilyn(i).Visible = True Next i End Sub

77 SPLIT FUNCTION

78 Marx Brother Quiz (Split Function)

79 Marx Brother Quiz (Split Function)

80 Marx Brother Quiz (Split Function)
Dim sAllAnswers As String Dim sIndivAnswers() As String ‘Dynamic array Private Sub Form_Load() sAllAnswers = "Groucho,Chico,Harpo,Zeppo,Gummo" End Sub Private Sub cmdCheck_Click() Dim i As Integer Dim bGotRight As Boolean sIndivAnswers = Split(sAllAnswers, ",") Parses sAllAnswers using comma as delimiter, places resulting tokens in dynamic array.

81 bGotRight = False For i = 0 To UBound(sIndivAnswers) If LCase(txtResponse.Text) = LCase(sIndivAnswers(i)) Then bGotRight = True Exit For End If Next i If bGotRight Then lblResult.Caption = "That is correct." Else lblResult.Caption = "Sorry, that is incorrect." End Sub


Download ppt "ARRAYS Variable Arrays, Control Arrays, Dynamic Variable Arrays, Dynamic Control arrays."

Similar presentations


Ads by Google