The Repetition Process in Visual Basic The Repetition

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) – 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 • Determinate loops 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 Sub. Form_Load int. Sum=0 int. Num. Values=0 End Sub

Form-level Variables

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 int. Num. Value as Integer, cur. Cost 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 (Evnt. Drvn. 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 -2 Code for Calculate Button (Evnt. Drvn. vbp) Private Sub cmd. Calc_Click() ’Declare variables and assign values Dim int. The. Value As Integer int. The. Value = CInt(txt. The. Value. text) ’Calculate New Sum and Number of Values entered int. Sum = int. Sum + int. The. Value’New summing statement int. Num. Values = int. Num. Values + 1’# entries(count) txt. Sum. Text = Str(int. Sum) txt. Num. Values. text = Str(int. Num. Values) ’Add value to list box and covert to string lst. Entries. Add. Item str(The. Value) txt. The. Value. text = "" ’Clear text box txt. The. Value. Set. Focus ’Set focus back to txt. The. Value End Sub

Use of Add. Item and Clear Methods • The Add. Item method is used to add items to a list box at run time, instead of design time • Form of Add. Item method lst. Entries. 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 lst. Entries. Clear

VB Code Box 5 -3 Code for cmd. Clear Button Private Sub cmd. Clear_Click() ’ Clear text boxes txt. The. Value. Text = "" txt. Sum. Text = "" txt. Num. Values. Text = "" ’Set form variables back to 0 int. Sum = 0 int. Num. Values = 0 lst. Entries. Clear ’Clear list box ’Set focus back to txt. The. Value. Set. Focus 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 Counter Variable For Statement Beginning Value For int. Counter = Ending Value Change Value 1 to 10 Step 1 int. Sum = int. Sum + int. Counter Next Statement Body of Loop

VB Code Box 5 -5 Code for cmd. Calc Event Procedure (For. Next. vbp) Private Sub cmd. Calc_Click() ’Declare variables and set Sum variable to 0 Dim int. The. Value as Integer, int. Sum as Integer Dim int. Num. Values as Integer, int. Counter as Integer int. Sum = 0 If txt. Num. Values. Text = "" Then ’Number not entered Msgbox "Please enter number of values to be summed" Exit Sub ’Do not go into loop End if int. Num. Values = CInt(txt. Num. Values. Text)’stor text entry For int. Counter = 1 to int. Num. Values int. The. Value = CInt(Input. Box("Enter next value")) int. Sum = int. Sum + int. The. Value ’Calculate sum lst. Entries. Add. Item Str(int. The. Value) ’List box value Next txt. Sum. Text = Str(int. Sum)’ integer to text/displays sum lst. Entries. Add. Item "Sum is " & str(int. Sum) End Sub

VB Code Box 5 -6 Code for cmd. Clear Event Procedure For. Next. vbp Private Sub cmd. Clear_Click() ’Clear text box txt. Num. Values. text = "" txt. Sum. Text = "" lst. Entries. Clear ’Clear list box ’Set focus to txt. Num. Values. Set. Focus 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 int. Counter as Integer For int. Counter = 0 to lst. Entries. List. Count - 1 Debug. Print lst. Entries. List(Counter) Next

VB Code Box 5 -7 Code to Print Contents of List Box to Printer Dim int. Counter as Integer For int. Counter = 0 to lst. Entries. List. Count - 1 Printer. Print lst. Entries. List(Counter) Next Printer. End. Doc

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 and Post-Test Loops

Pre-test Loop Processing Do 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 Processing Do 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 Processing Do 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 Processing Do 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 int. Value = 10 Do While int. Value > 0 Msg. Box "Value = " & int Value = int. Value Loop OR int. Value = 10 Do Until int. Value <=0 Msg. Box "Value = " & int. Value = int. Value Loop str(int. Value) - 2

Using the Post Test Do Loop While / Do Until Loops to Count Backwards int. Value = 10 Do Msg. Box "Value = " & int. Value = int. Value Loop While int. Value > 0 OR int. Value = 10 Do Msg. Box "Value = " & int. Value = int. Value Loop Until int. Value <=0 str(int. Value) -2

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 filenames assigned 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 end of the file called the EOF (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 5Sum. Data. 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 -must match the file number in the Open Statement list of variables - names for which data is entered Example: Input #10, int. The. Value

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 cmd. Calc_Click() Dim int. The. Value As Integer, int. Sum As Integer Dim int. Num. Values As Integer Open "a: Chapter 5Sum. Data. txt" For Input As #10 int. Sum = 0’set variable to 0 int. Num. Values = 0 ’set variable to 0 Do Until EOF(10) ’Input to end of file Input #10, int. The. Value ’inputs data file int. Sum = int. Sum + int. The. Value ’sums int. Num. Values = int. Num. Values + 1’counts items lst. Entries. Add. Item str(The. Value) Loop ’# of entries in data file txt. Num. Values. text = Str(int. Num. Values) txt. Sum. Text = Str(int. Sum)’display sum in text box lst. Entries. Add. Item "Sum is " & str(int. Sum) Close #10 ’Close data file End Sub

VB Code Box 5 -11 Code for cmd. Clear Event Procedure Private Sub cmd. Clear_Click() txt. Num. Values. Text = "" txt. Sum. Text = "" lst. Entries. 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 Add. Item, 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. Add. Item method and a text box and if sorted property is true name is added in appropriate order – cbo. Members. Additem txt. Cust. Name. text • Items can be removed from a combo or list box with the Remove. Item method which requires that number of the item to be remove be given. However, to remove a selected item, use the List. Index property, eg, cbo. Members. Remove. Item cbo. Members. List. Index

Application to Vintage Video

Pseudocode for Filling Combo Box Open file Repeat Until end of file encountered Input Name Transfer name to combo box end of loop Close file

VB Code Box 5 -13 Code for Form_Load Event Private Sub Form_Load() ’Declare variable Dim str. Name As String lst. Videos. Add. Item "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 cbo. Members. Add. Item Name Loop Close #1’Close data file #1 End Sub

Code to Add Name to List (cmd. Add Command Button) Private Sub cmd. Add_Click() If txt. Cust. Name. txt <> “” Then cbo. Members. Add. Item txt. Cust. Name. Text End If

VB Code Box 5 -16 Code to Delete Name from List Private Sub cmd. Delete_Click() ’ Check to see if no name selected or combo box is empty If cbo. Members. List. Index > -1 Then cbo. Members. Remove. Item cbo. Members. List. Index Else ’Display message box Msg. Box "No name selected or list is empty" End If End Sub

VB Code Box 5 -14 Partial Revised Code for End of cmd. Calc cur. Price = CCur(txt. Video. Price)’Find this line!!! cur. Total. Cost = cur. Total. Cost + cur. Price 'Add price to total cost cur. Taxes = cur. Total. Cost * cur. Tax. Rate 'Compute taxes on total cost cur. Amount. Due = cur. Total. Cost +cur Taxes 'Compute amount due txt. Total. Cost. Text = Format(cur. Total. Cost, "Currency") txt. Taxes. Text = Format(cur. Taxes, "currency") txt. Amount. Due. Text = Format(cur. Amount. Due, "currency") txt. Video. Price. Text = Format(cur. Price, "currency") lst. Videos. Add. Item txt. Video. Name. Text & _ " " & txt. Video. Price. Text lst. Types. Text = "" txt. Video. Name. Text = "" txt. Video. Price. Text = "" txt. Video. Name. Set. Focus 'Set Focus to video name text box End Sub

VB Code Box 5 -15 Code for cmd. Print Event Procedure Private Sub cmd. Print_Click() Dim int. Number As Integer, int. Counter As Integer lst. Videos. Add. Item "Total video price " + _ txt. Total. Cost. Text ’Total price & lst. Videos. Add. Item "Taxes " + txt. Taxes. Text’Taxes lst. Videos. Add. Item "Total price = " + _ txt. Amount. Due. Text ’Total price $ lst. Videos. Add. Item "Thanks for your business!" int. Number = lst. Videos. List. Count For int. Counter = 0 To Number - 1 Debug. Print lst. Videos. List(int. Counter) 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: chapter 5members. txt” for Output as #10 • Use a Write statement to save changes – Example Write #n, variable list – Write #10, Member. Name

VB Code Box 5 -17 Code for cmd. Exit Event Procedure Private Sub cmd. Exit_Click() Dim int. Num. Members As Integer, str. Member. Name As String Dim int. Counter As Integer Open "a: chapter 5members. txt" For Output As #10 int. Num. Members = cbo. Members. List. Count For int. Counter = 0 To int. Num. Members - 1 str. Member. Name = cbo. Members. List(Counter) Write #10, str. Member. Name Next Close #10 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.
- Slides: 48