540 likes | 882 Views
The Repetition Process in Visual Basic. The Repetition Process. The capability to repeat one or more statements as many times as necessary is what really sets a computer apart from other devices All loops have two parts: the body of the loops (the statements being repeated)
E N D
The Repetition Process • The capability to repeat one or more statements as many times as necessary is what really sets a computer apart from other devices • All loops have two parts: • the body of the loops (the statements being repeated) • a termination condition that terminates the loop • Failure to have a valid termination condition can lead to an endless (indefinite)loop
Types of Loops • There are three types of loops: • Event-driven loops are repeated by the user causing an event to occur, such as by clicking a command button • Determinateloops repeat a known number of times • Indeterminate loops repeat an unknown number of times • Variables should be initialized to zero before being used in a loop
Summing Vs. Counting • Summing - adding some value to an existing sum • Example 2+3+5=10 • Counting - adding one to a counter • Example - 1+1+1+1=4
Variable Scope and Local Variables • Event-driven loops are repeated by user causing an event to occur--clicking a button • Variable scope is important for loops. • Variables in event procedures are local i.e, specific to a command button, and are reset to zero when procedure terminates. Other events do not know about this variable
Form Level Variable • Variables defined at form level are known to all procedures on the form and retain their value between events**** • Form-level variables are declared in the Declarations procedure of the General object • Should initialize form level variables to 0 with this syntax • Private SubForm_Load intSum=0 intNumValues=0 End Sub
Static Variable and Project Level Variable • Static variables retain their value between events but are local to event procedure**** • Declared with Static keyword Syntax: Static Variable as Type, Variable As Type Static intNumValue as Integer, curCost as Currency • Project variables are known to the whole project, with multiple forms and are contained in a module of their own (Chapter 7)****
Pseudocode for Calculate Button(EvntDrvn.vbp) • Sum and count procedure • Input Value • Add Value to Sum • Increment Number of values by 1 • Display Sum and Number of values • Add value to list box • End procedure
VB Code Box 5-2Code for Calculate Button (EvntDrvn.vbp) • Private Sub cmdCalc_Click() • ’Declare variables and assign values • Dim intTheValue As Integer • intTheValue = CInt(txtTheValue.text) • ’Calculate New Sum and Number of Values entered • intSum = intSum + intTheValue’New sum summing statement) • intNumValues = intNumValues + 1’# entries(count) • txtSum.Text = Str(intSum) • txtNumValues.text = Str(intNumValues) • ’Add value to list box and covert to string • lstEntries.AddItem str(TheValue) • txtTheValue.text = "" ’Clear text box txtTheValue • txtTheValue.SetFocus ’Set focus back to txtTheValue • End Sub
Use of AddItem and Clear Methods • The AddItem method is used to add items to a list box at run time, instead of design time • Form of AddItem method lstEntries.Additem str(variable) • Always add a string to list box since it contains text • The Clear method clears a list box and a combo box lstEntries.Clear
VB Code Box 5-3Code for cmdClear Button • Private Sub cmdClear_Click() • ’ Clear text boxes • txtTheValue.Text = "" • txtSum.Text = "" • txtNumValues.Text = "" • ’Set form variables back to 0 • intSum = 0 • intNumValues = 0 • lstEntries.Clear ’Clear list box • ’Set focus back to txtTheValue • txtTheValue.SetFocus • End Sub
Determinate Loops Using For-Next Loop Best way to create a determinate loop is to use a For-Next Loop (used when # of repetitions known in advance****) Form of For-Next Loop: For variable = start value to end value Step change value statements that compose body of loop Next variable where variable = the counter variable in the loop start value = the beginning value of the counter variable end value = the ending value of the counter variable change value = the amount the counter variable changes each time through the loop(if omitted is 1) Next variable = the end of the For loop
Example of For-Next Loop Beginning Ending Change Counter Value Value Value Variable For For intCounter = 1 to 10 Step 1 Statement intSum = intSum + intCounter Next Statement Next intCounter Body of Loop
VB Code Box 5-5Code for cmdCalc Event Procedure (ForNext.vbp) • Private Sub cmdCalc_Click() • ’Declare variables and set Sum variable to 0 • Dim intTheValue as Integer, intSum as Integer • Dim intNumValues as Integer, intCounter as Integer • intSum = 0 • If txtNumValues.Text = "" Then ’Number not entered • Msgbox "Please enter number of values to be summed" • Exit Sub ’Do not go into loop • End if • intNumValues = CInt(txtNumValues.Text)’stor text entry • For intCounter = 1 to intNumValues • intTheValue = CInt(InputBox("Enter next value")) • intSum = intSum + intTheValue ’Calculate sum • lstEntries.AddItem Str(intTheValue) ’List box value • Next • txtSum.Text = Str(intSum)’ integer to text/displays sum • lstEntries.AddItem "Sum is " & str(intSum) • End Sub
VB Code Box 5-6Code for cmdClear Event ProcedureForNext.vbp • Private Sub cmdClear_Click() • ’Clear text box • txtNumValues.text = "" • txtSum.Text = "" • lstEntries.Clear ’Clear list box • ’Set focus to txtNumValues • txtNumValues.SetFocus • End Sub
Printing a List • To print the contents of listbox, use the Listcount and List() properties of the list box • Listcount is the number of items in list box • List(Counter) is equal to the contents of the corresponding list box Lst() property runs from 0 to Listcount -1 • Code to print contents of list box to Immediate Window: Dim intCounter as Integer For intCounter = 0 to lstEntries.ListCount - 1 Debug.Print lstEntries.List(Counter) Next
VB Code Box 5-7Code to Print Contents of List Box to Printer Dim intCounter as Integer For intCounter = 0 to lstEntries.ListCount - 1 Printer.Print lstEntries.List(Counter) Next Printer.EndDoc
Indeterminate Loops • Indeterminate loops run for an unknown number of repetitions until a condition becomes true or while a condition is true • Four types of indeterminate loops • Until loop with termination condition before body of loop • While loop with termination condition before body of loop • Until loop with termination condition after body of loop • While loop with termination condition after body of loop • Pre-Test loops have termination condition before loop body • Post-test loops have termination condition after loop body
Form of Pre - and Post-Test Loops • The form of the pre-test loops is: Do Until (or While) condition body of loop Loop • The form of the post-test loops is: Do body of loop Loop Until (or While) condition
Pre-test Loop ProcessingDo While Loops • In a Do While Loop, if condition being tested is True, then control is transferred to the body of the loop for another repetition of the loop • In a Do While Loop, if condition being tested is False, control is transferred out of the loop and to the statement immediately following the Loop statement
Pre-test Loop ProcessingDo Until Loops • In a Do Until Loop, if the condition being tested is False, then control is transferred to the body of the loop for another repetition of the loop • In a Do Until Loop, if condition being tested is TRUE, control is transferred out of the loop and to the statement immediately following the Loop statement
Post-test Loop ProcessingDo While Loops • In a post-test loop, the body of the loop is executed and then the condition is tested. • In a post-test, Do While Loop, if condition being tested in the Loop While statement is True, then control is transferred back to the Do statement at the top of the loop and then to the body of a loop for another repetition of the loop. • In a post-test Do While Loop, if condition being tested in the Loop While statement is False, then control is transferred out of the loop and to the statement immediately following the Loop While statement
Post-test Loop ProcessingDo Until Loops • In a post-test, Do Until Loop, if condition being tested in the Loop Until statement is False, then control is transferred to the Do statement at the top of the loop and then to the body of the loop for another repetition of the loop • In a post-test Do Until Loop, if condition being tested in the Loop Until statement is True, then control is transferred out of the loop and to the statement immediately following the Loop Until Statement
Using the Pretest Do While /Do Until Loops to Count Backwards intValue = 10 Do While intValue > 0 MsgBox "Value = " & str(intValue) int Value = intValue - 2 Loop OR intValue = 10 Do Until intValue <=0 MsgBox "Value = " & str(intValue) intValue = intValue - 2 Loop
Using the Post Test Do Loop While /Do Until Loops to Count Backwards intValue = 10 Do MsgBox "Value = " & str(intValue) intValue = intValue -2 Loop While intValue > 0 OR intValue = 10 Do MsgBox "Value = " & str(intValue) intValue = intValue -2 Loop Until intValue <=0
Processing an Unknown Number of Values from a File • A data file is a collection of data stored on magnetic or optical secondary storage in the form of records. • A record is a collection of one or more data items that are treated as a unit. • Files are identified by the computer’s operating system with filenamesassigned by the user. • Files are important to processing data into information because they provide a permanent method of storing large amounts of data that can be input whenever needed for processing into information
Three Types of Files • Sequential access files – files from which the data records must be input in the same order that they were placed on the file. • Direct access files – files that can be input in any order • Database files – entered with a database management system and not input directly into a VB project
Using Sequential Access Files • Sequential access files must be read in same order as they are created so they replicate the action of entering data from a keyboard. • The number of records on a sequential access file is often unknown, but there is an invisible binary marker at the endof the file called theEOF (end of file) marker. **** • Use a Do While loop or a Do Until loop to input data from sequential access file. • Loops can input data until the EOF marker is encountered (or while it has not been encountered). • Create sequential access files by using the Notepad text editor because it saves in.txt format automatically
Opening and Inputting Data from a File • Files must be opened with the Open statement: Open “filename" for Input as #n filename also includes the drive and folder n is file number between 1 and 511 Example: Open “a:\chapter 5\SumData.txt” for Input as #10 • To input data from a file once it has been opened , use the Input #n, statement Input #n, list of variables #n -mustmatch the file number in the Open Statement list of variables - names for which data is entered Example: Input #10, intTheValue
Using a Do Loop and Closing Sequential Files • Using an Until loop to input data from file Do Until EOF(n) Input #n, list of variables Loop • Opened Files must be closed at end of procedure Close #n Example: Close #10
VB Code Box 5-10 Code to Input and Sum Values from File Private Sub cmdCalc_Click() Dim intTheValue As Integer, intSum As Integer Dim intNumValues As Integer Open "a:\Chapter5\SumData.txt" For Input As #10 intSum = 0’set variable to 0 intNumValues = 0 ’set variable to 0 Do Until EOF(10) ’Input to end of file Input #10, intTheValue ’inputs data file intSum = intSum + intTheValue ’sums intNumValues = intNumValues + 1’counts items lstEntries.AddItem str(TheValue) Loop ’# of entries in data file txtNumValues.text = Str(intNumValues) txtSum.Text = Str(intSum)’display sum in text box lstEntries.AddItem "Sum is " & str(intSum) Close #10 ’Close data file End Sub
VB Code Box 5-11Code for cmdClear Event Procedure • Private Sub cmdClear_Click() • txtNumValues.Text = "" • txtSum.Text = "" • lstEntries.Clear • End Sub
The Combo Box • A combo box is a combination of a text box and a list box. It typically a drop-down list box • It has a text box portion that is displayed at all times and a drop-down list of items that can be displayed by clicking on the down arrow. • One property of note for the combo box is the Style property, which can be set at design time to Drop Down combo (the default), Simple Combo, or Drop Down list. Its prefix is cbo . • The combo box has all the properties and methods of the list box including the AddItem, Listcount, and list properties.
More on Combo Boxes • The default event for the Combo box is the Change event--to use the Click event, you must change to it. • The Sorted property is a useful property for the combo and list boxes that arranges the items in the box. • If property is True names are in order last name , first name • Items can be added by using .AddItem method and a text box and if sorted property is true name is added in appropriate order • cboMembers.Additem txtCustName.text • Items can be removed from a combo or list box with the RemoveItem method which requires that number of the item to be remove be given. However, to remove a selected item, use the ListIndex property, eg, cboMembers.RemoveItem cboMembers.ListIndex
Pseudocode for Filling ComboBox • Open file • Repeat Until end of file encountered • Input Name • Transfer name to combo box • end of loop • Close file
VB Code Box 5-13Code for Form_Load Event • Private Sub Form_Load() • ’Declare variable • Dim strName As String • lstVideos.AddItem "Welcome to Vintage Videos" • ’Open data file #1 • Open "a:\members.txt" For Input As #1 • Do Until EOF(1) ’Input names and add to combo box • Input #1, Name • cboMembers.AddItem Name • Loop • Close #1’Close data file #1 • End Sub
Code to Add Name to List(cmdAdd Command Button) Private Sub cmdAdd_Click() If txtCustName.txt <> “” Then cboMembers.AddItem txtCustName.Text End If
VB Code Box 5-16Code to Delete Name from List Private Sub cmdDelete_Click() ’ Check to see if no name selected or combo box is empty If cboMembers.ListIndex > -1 Then cboMembers.RemoveItem cboMembers.ListIndex Else ’Display message box MsgBox "No name selected or list is empty" End If End Sub
VB Code Box 5-14 Partial Revised Code for End of cmdCalc curPrice = CCur(txtVideoPrice)’Find this line!!! curTotalCost = curTotalCost + curPrice 'Add price to total cost curTaxes = curTotalCost * curTaxRate 'Compute taxes on total cost curAmountDue = curTotalCost +cur Taxes 'Compute amount due txtTotalCost.Text = Format(curTotalCost, "Currency") txtTaxes.Text = Format(curTaxes, "currency") txtAmountDue.Text = Format(curAmountDue, "currency") txtVideoPrice.Text = Format(curPrice, "currency") lstVideos.AddItem txtVideoName.Text & _ " " & txtVideoPrice.Text lstTypes.Text = "" txtVideoName.Text = "" txtVideoPrice.Text = "" txtVideoName.SetFocus 'Set Focus to video name text box End Sub
VB Code Box 5-15Code for cmdPrint Event Procedure Private Sub cmdPrint_Click() Dim intNumber As Integer, intCounter As Integer lstVideos.AddItem "Total video price " + _ txtTotalCost.Text ’Total price & lstVideos.AddItem "Taxes " + txtTaxes.Text’Taxes lstVideos.AddItem "Total price = " + _ txtAmountDue.Text ’Total price $ lstVideos.AddItem "Thanks for your business!" intNumber = lstVideos.ListCount For intCounter = 0 To Number - 1 Debug.Print lstVideos.List(intCounter) Next End Sub
Saving Updates to List • Uses an Open statement also • Open ” filename” for Output as #n • filename includes drive and path • #n =number of file • Example: • Open “a:\chapter5\members.txt” for Output as #10 • Use a Write statement to save changes • Example Write #n, variable list • Write #10, MemberName
VB Code Box 5-17Code for cmdExit Event Procedure Private Sub cmdExit_Click() Dim intNumMembers As Integer, strMemberName As String Dim intCounter As Integer Open "a:\chapter5\members.txt" For Output As #10 intNumMembers = cboMembers.ListCount For intCounter = 0 To intNumMembers - 1 strMemberName = cboMembers.List(Counter) Write #10, strMemberName Next Close #10 End End Sub
Creating an Executable File • An executable file is one that can be executed on any computer on which it is installed. • Creating an executable file in VB is accomplished with the File|Make filename.exe menu selection. • Once an executable file is created, a shortcut to it can be created by right-clicking the file name in Windows Explorer and selecting Create Shortcut. • Drag the shortcut to the desktop.
Nested Loops • A Nested loop is a loop within a loop. Must complete the inner loop within the outer loop. • Nested For-Next loops have a For-Next loop within a For-Next loop in which the inner loop will go through all its values for each value of the outer loop. • Three key programming rules to remember about using nested For-Next loops: • Always use different counter variables for the outer and inner For-Next loops.**** • Always have the Next statement for the inner For-Next loop before the Next statement for the outer For-Next loop. • Always include the counter variable in the Next statements to distinguish between the loops.
Debugging Loops • Debug a loop by inserting a Debug.Print command in the loop to print to the Immediate Window. • Add a Quick Watch by locating the pointer on a variable and clicking the eyeglass icon on the Debug Toolbar. The values for this variable will be shown in the Watch Window. • Use the Locals window to display the values of variables local to a procedure. • Use the Toggle Breakpoint icon to pause execution at a designated line in the code and then use the various windows to view the values for variables.