Microsoft Visual Basic 2010: ReloadedFourth Edition Chapter Six Repeating Program Instructions
Repetition Structure DoWhile...Loop, DoUntil...Loop, DoLoop...While, and DoLoop...Until repetition statements String Concatenation Using ListBoxes Display a dialog box using the InputBox function Enable and disable a control Refresh the screen Delay program execution Overview
The Repetition Structure • Repetition structure (or loop): a structure that repeatedly processes one or more program instructions until a condition is met • Looping condition: the requirement for repeating the instructions • Loop exit condition: the requirement for not repeating the instructions • Pretest loop: condition is evaluated before the instructions within the loop are processed (0 or more times) • Posttest loop:condition is evaluated after the instructions within the loop are processed (at least once)
DoWhile...Loop Repetition Statement • A repetition statement can repeat actions, depending on the value of a condition. • If you go to the grocery store with a list of items to purchase, you go through the list until you have each item: Do while there are more items on my shopping list Put next item in cart Cross it off my list
DoWhile...Loop Repetition Statement • Using a DoWhile...Loop statement, this codefinds the first power of 3 greater than 50. Dim product As Integer = 3 Do While product <= 50 product *= 3Loop • The condition in the DoWhile...Loopstatement, product<=50, is referred to as theloop-continuationcondition. • When the loop-continuation condition becomes false, the DoWhile...Loop statement finishes executing.
DoUntil...Loop Repetition Statement • These statements describe the repetitive actions that occur during a shopping trip: Do until there are no more items on my shopping list Put next item in cart Cross it off my list • Statements in the body of a DoUntil...Loop are executed repeatedly for as long as the loop-termination condition remains False. • This is known as aloop-termination condition.
DoUntil...Loop Repetition Statement • Using aDoUntil...Loop, this code finds the first power of3 larger than 50: Dim product As Integer = 3 Do Until product > 50 product *= 3Loop • Failure to provide the body of a DoUntil...Loop statement with an action that eventually causes the condition in the DoUntil...Loop to become true creates an infinite loop.
Do...LoopWhile Repetition Statement • Do...LoopWhile repetition statement is similar to the Do...WhileLoop statement, except that the loop-termination condition is tested after the loop body is performed. • Consider the example of packing a suitcase: • You place an item in the suitcase, then determine whether the suitcase is full. • As long as the suitcase is not full, you continue to put items in the suitcase.
Do...LoopWhile Repetition Statement • The following application segment displays the numbers 1 through 3 in a ListBox: DimcounterAsInteger=1DodisplayListBox.Items.Add(counter)counter+=1LoopWhilecounter<=3
Do...LoopUntil Repetition Statement • The Do...LoopUntil statement is similar to the Do...UntilLoop statement, except that the loop-termination condition is tested after the loop body is performed. • Imagine that you place an item in the suitcase, then determine whether the suitcase is full. As long as the condition “the suitcase is full” isFalse, you continue to put items into the suitcase.
Do...LoopUntil Repetition Statement • This application segment displays the numbers 1 through 3 in a ListBox: DimcounterAsInteger=1DodisplayListBox.Items.Add(counter)counter+=1LoopUntilcounter>3
CarPayment Calculator Application • Typically, banks offer car loans for periods ranging from two to five years. Borrowers repay the loans in monthly installments. The amount of each monthly payment is based on the length of the loan, the amount borrowed and the interest rate. Create an application that allows the customer to enter the price of a car, the down-payment amount and the annual interest rate of the loan. The application should display the loan’s duration in months and the monthly payments for two-, three-, four- and five-year loans. The variety of options allows the user to easily compare repayment plans and choose the most appropriate.
CarPayment Calculator Application Results displayed in tabular format ListBox control
Designing the CarPaymentCalculator Application When the user clicks the Calculate Button Initialize loan length to two years Clear the ListBox of any previous calculation results Add a header to the ListBox Get down payment from a TextBox Get sticker price from a TextBox Get annual interest rate from a TextBox Calculate loan amount (sticker price – down payment) Calculate monthly interest rate (annual interest rate / 12)
Designing the CarPaymentCalculator Application Do while loan length is less than or equal to five years Convert the loan length in years to number of months Calculate monthly payment based on loan amount, monthly interest rate and loan length in months Insert result into ListBox Increment loan length in years by one year
Clearing and Changing a ListBox’s Contents • The ListBox is initially cleared and then displays the number of monthly payments and the amount per payment. • To clarify what information is being displayed, a line of text—called aheader—is added to the ListBox by the Method Add
CarPayment Calculator Application ListBox header
Concatenate Strings • The ampersand symbol (&) is called the string-concatenation operator. This operator combines its two operands into one string value. • The constant ControlChars.Tab inserts a tab character into the string.
Calculating the Monthly Payment Amounts witha DoWhile...Loop Repetition Statement • This loop is an example ofcounter-controlledrepetition. • This uses a counter (years) to control the number of times that a set of statements executes. • Counter-controlled repetition also is called definite repetition, because the number of repetitions is known before the repetition statement begins.
Accessing Items in a List Box Figure 6-27: How to access an item in a list box
The SelectedItem and SelectedIndex Properties • SelectedItem property: • Contains the value of the selected item in the list • If nothing is selected, it contains the empty string • SelectedIndex property: • Contains the index of the selected item in the list • If nothing is selected, it contains the value -1 • Default list box item: the item that is selected by default when the interface first appears
The SelectedItem and SelectedIndex Properties Figure 6-29: Item selected in the animalListBox
The SelectedItem and SelectedIndex Properties Figure 6-31: How to select the default list box item
ClassAverage Application • A teacher regularly gives quizzes to a class of 10 students. The grades on these quizzes are integers in the range from 0 to 100 (0 and 100 are both valid grades). The teacher would like you to develop an application that computes the class average forone quiz.
ClassAverage Application • Enter nine other grades between 0 and 100. • Note that the Add GradeButton is disabled once you have entered 10 grades (Fig. 10.3). Disabled Add GradeButton Ten quiz grades entered Figure 10.3|Class Average application after 10 grades have been input.
ClassAverage Application • Click the AverageButton to calculate theaverage of the 10 quizzes (Fig. 10.4). Label displaying average Click to calculate class average Figure 10.4|Displaying the class average.
Designing the Class Average Application When the user clicks the Add Grade Button If an average has already been calculated for a set of grades Clear the output Label and the ListBox Retrieve grade entered by user in the Enter grade:TextBox Display the grade in the ListBox Clear the Enter grade: TextBox Transfer focus to the Enter grade: TextBox If the user has entered 10 grades Disable the Add Grade Button Transfer focus to the Average Button
Designing the Class Average Application When the user clicks the Average Button Set total to zero Set grade counter to zero Do Read the next grade in the ListBox Add the grade to the total Add one to the grade counter Loop While the grade counter is less than 10 Calculate the class average by dividing the total by 10 Display the class average Enable the Add Grade Button Transfer focus to the Enter grade: TextBox
Checking if Average Has Been Calculated • This code tests whether averageResultLabel displays any text by comparing the Text property’s value to the empty string. Figure 10.10|Clearing the output Label and ListBox after a calculation.
Adding Entered Grades to ListBox • Line 13 (Fig. 10.11) Adds the grade entered in gradeTextBox to gradesListBox’s Items property. The grade is displayed in the ListBox. • Method Clear deletes the grade from the TextBox so that the next grade can be entered. Figure 10.11|Adding the grade input to the ListBox andclearing the Entergrade:TextBox.
Transferring the Focus to a Control • Calling gradeTextBox’s Focus method places the cursor in the TextBox for the next grade input (Fig. 10.12). • This process is called transferring the focus. Figure 10.12|Transferring the focus to the TextBox control.
Disabling a Button • Your application should accept exactly 10 grades. • Items’s Count property returns the number of items displayed in the Grade list:ListBox. • If 10 grades have been entered, addButton’s Enabled property is set to False (Fig. 10.13). Figure 10.13|Application accepts only 10 grades.
Calculating the Class Average • Use the Integertotal (Figure 10.14 ) to calculate the sum of the 10 grades. • The result of the averaging calculation can be a floating-point value; therefore, you declare a Double variable to store the class average. Figure 10.14|Initialization phase of class-average calculation.
Calculating the Class Average (Cont.) • The Do...LoopUntil statement should iterate until the value of gradeCounter is greater than or equal to 10. • The items in aListBoxare accessed by their position number, starting from position number0. Figure 10.15|Do...LoopUntil summing grades.
Calculating the Class Average (Cont.) • After the average is displayed, the application resets, and another list of grades can be entered. Figure 10.16|Displaying the result of the average calculation.
Adding Items to a List Box (cont'd.) Figure 6-19: How to use the Items collection’s Add method
The InputBox Function • InputBox function: displays a predefined dialog box that allows the user to enter data • Contains a text message, an OK button, a Cancel button, and an input area • InputBox function returns: • The user’s entry if the user clicks the OK button • An empty string if the user clicks the Cancel button or the Close button on the title bar
The InputBox Function • InputBox function arguments: • prompt: the message to display inside the dialog box • title: the text to display in the dialog box’s title bar • defaultResponse: a prefilled value for the user input
The InputBox Function Figure 6-16: How to use the InputBox function (cont'd.)
The Color Viewer Application • Enabled property: used to enable or disable a control • When False, the control appears dimmed (grayed out), indicating it is not available for use • Refresh method: ensures that the computer processes any previous lines of code that affect the interface’s appearance • Sleep method: delays program execution • Argument is specified in milliseconds
The Color Viewer Application Figure 6-38: MainForm in the Color Viewer application
The Color Viewer Application Figure 6-39: View Colors button’s Click event procedure