Lect06 Introducing The Do While... Loop and Do Until... Loop Repetition Statements

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 39

1

T U T O R I A L

Car Payment
9
Calculator Application
Introducing the Do While...Loop
and Do Until...Loop Repetition
Statements

 2009 Pearson Education, Inc. All rights reserved.


2

Outline

9.1 Test-Driving the Car Payment Calculator


Application
9.2 Do While...Loop Repetition Statement
9.3 Do Until...Loop Repetition Statement
9.4 Constructing the Car Payment Calculator
Application

 2009 Pearson Education, Inc. All rights reserved.


3

Objectives

In this tutorial you will learn:


■ Use the Do While...Loop and
Do Until...Loop repetition statements to
execute statements in an application repeatedly.
■ Use counter-controlled repetition.
■ Display information in ListBoxes.
■ Concatenate strings.

 2009 Pearson Education, Inc. All rights reserved.


4
9.1 Test-Driving the Car Payment
Calculator Application
Application Requirements

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.

 2009 Pearson Education, Inc. All rights reserved.


5
Test-Driving the Car Payment
Calculator Application

■ Note the new GUI control—the ListBox control,


which allows users to view and/or select from multiple
items in a list (Fig. 9.1).

ListBox control

Figure 9.1 | Car Payment Calculator application before data has been entered.

 2009 Pearson Education, Inc. All rights reserved.


6
Test-Driving the Car Payment
Calculator Application (Cont.)

■ Enter data to test the application (Fig. 9.2).

Figure 9.2 | Car Payment Calculator application after data has been entered.

 2009 Pearson Education, Inc. All rights reserved.


7
Test-Driving the Car Payment
Calculator Application (Cont.)

■ Click the Calculate Button.


■ The application displays the monthly payment
amounts in the ListBox (Fig. 9.3) in a tabular format.

Results displayed in tabular format

Figure 9.3 | Car Payment Calculator application displaying calculation results.

 2009 Pearson Education, Inc. All rights reserved.


8

9.2 Do While...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

 2009 Pearson Education, Inc. All rights reserved.


9

9.2 Do While...Loop Repetition Statement (Cont.)

■ Using a Do While...Loop statement, this code


finds the first power of 3 greater than 50.
Dim product As Integer = 3
Do While product <= 50
product *= 3
Loop
■ The condition in the Do While...Loop
statement, product <= 50, is referred to as the
loop-continuation condition.
■ When the loop-continuation condition becomes
false, the Do While...Loop statement finishes
executing.
 2009 Pearson Education, Inc. All rights reserved.
10

Good Programming Error


Provide in the body of every Do While...Loop
statement an action that eventually causes the condition
to become false. If you do not, the repetition statement
never terminates, causing an error called an infinite loop.
Such an error causes the application to “hang up.” When
an infinite loop occurs in your application, return to the
IDE and select Debug > Stop Debugging.

 2009 Pearson Education, Inc. All rights reserved.


11

9.2 Do While...Loop Repetition Statement (Cont.)

■ The UML activity diagram in Fig. 9.4 illustrates the


flow of control in the preceding Do While...Loop
repetition statement.

Figure 9.4 | Do While...Loop repetition statement UML activity diagram.

 2009 Pearson Education, Inc. All rights reserved.


12

9.2 Do While...Loop Repetition Statement (Cont.)

■ The transition arrow emerging from the action


state points back to the merge, creating a loop.
■ The UML’s diamond-shaped merge symbol joins
two flows of activity into one.

 2009 Pearson Education, Inc. All rights reserved.


13

9.3 Do Until...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 Do Until...Loop are
executed repeatedly for as long as the loop-
termination condition remains False.
– This is known as a loop-termination condition.

 2009 Pearson Education, Inc. All rights reserved.


14

9.3 Do Until...Loop Repetition Statement (Cont.)

■ Using a Do Until...Loop, this code finds the first


power of 3 larger than 50:
Dim product As Integer = 3
Do Until product > 50
product *= 3
Loop

 2009 Pearson Education, Inc. All rights reserved.


15

Good Programming Error


Failure to provide the body of a Do Until...Loop
statement with an action that eventually causes the
condition in the Do Until...Loop to become true
creates an infinite loop.

 2009 Pearson Education, Inc. All rights reserved.


16

9.3 Do Until...Loop Repetition Statement (Cont.)

■ The UML activity diagram in Fig. 9.5 illustrates the


flow of control for the Do Until...Loop repetition
statement.

Figure 9.5 | Do Until...Loop repetition statement UML activity diagram.

 2009 Pearson Education, Inc. All rights reserved.


17
9.4 Constructing the Car Payment
Calculator 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)

 2009 Pearson Education, Inc. All rights reserved.


18
9.4 Constructing the Car Payment
Calculator Application (Cont.)

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

 2009 Pearson Education, Inc. All rights reserved.


19
Action/Control/Event (ACE) Table for the
Car Payment Calculator
■ Use an ACE table to convert pseudocode into Visual
Basic (Fig. 9.6).
Action Control Event
Label all the application’s controls PriceLabel, Application is run
downPaymentLabel,
interestLabel

calculateButton Click

Initialize loan length to two years

Clear the ListBox of any previous calculation paymentsListBox


results

Add a header to the ListBox paymentsListBox

Get down payment from a TextBox downPaymentTextBox

Get sticker price from a TextBox PriceTextBox

Get interest rate from a TextBox interestTextBox

Figure 9.6 | Car Payment Calculator application ACE table. Part (1 of 2.)

 2009 Pearson Education, Inc. All rights reserved.


20
Action/Control/Event (ACE) Table for the
Car Payment Calculator (Cont.)

Action Control Event


Get interest rate from a TextBox interestTextBox

Calculate loan amount

Calculate monthly interest rate

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 paymentsListBox

Increment loan length in years by one


year

Figure 9.6 | Car Payment Calculator application ACE table. Part (2 of 2.)

 2009 Pearson Education, Inc. All rights reserved.


21
Adding a ListBox to the Car
Payment Calculator Application

■ Add a ListBox control from the Toolbox.

■ Change the ListBox’s Name property to


paymentsListBox. Set the Location property to
24, 166 and the Size property to 230, 94 (Fig. 9.7).

Figure 9.7 | ListBox added to Car Payment Calculator application’s Form.

 2009 Pearson Education, Inc. All rights reserved.


22

Good Programming Practice


Append the ListBox suffix to all ListBox control names.

 2009 Pearson Education, Inc. All rights reserved.


23

GUI Design Tip


A ListBox should be large enough to display all of its
contents or large enough that scrollbars can be used
easily.

 2009 Pearson Education, Inc. All rights reserved.


24

Using Code to Change a ListBox’s Contents

■ Double click the Calculate Button to generate the


empty event handler (Fig. 9.8).
■ Content can be added and deleted from the ListBox by
using its Items property.
– The Items property returns an object that contains a list of
items displayed in the ListBox.

Figure 9.8 | Clearing the contents of a ListBox.

 2009 Pearson Education, Inc. All rights reserved.


25
Using Code to Change a
ListBox’s Contents (Cont.)

■ The ListBox displays the number of monthly payments


and the amount per payment.
■ To clarify what information is being displayed, a line of text
—called a header—is added to the ListBox by the
Method Add (lines 10–11 of Fig. 9.9)

Figure 9.9 | Adding a header to a ListBox.

 2009 Pearson Education, Inc. All rights reserved.


26

GUI Design Tip


Use headers in a ListBox when you are displaying
tabular data. Adding headers improves readability by
describing the information that is displayed in the
ListBox.

 2009 Pearson Education, Inc. All rights reserved.


27
Using Code to Change a
ListBox’s Contents (Cont.)

■ 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.

 2009 Pearson Education, Inc. All rights reserved.


28

Declaring Variables and Retrieving User Input

■ The calculation requires the length in months, but the


loop-continuation condition uses the number of years
(Fig. 9.10).

Variables to store the length


of the loan
Variables to store user input

Variables to store
calculation results

Figure 9.10 | Variables for the Car Payment Calculator application.

 2009 Pearson Education, Inc. All rights reserved.


29
Declaring Variables and Retrieving
User Input (Cont.)

■ Note that line 26 (Fig. 9.11) divides the interest rate


by 100 to obtain the decimal equivalent
– For example, 5% becomes .05

Figure 9.11 | Retrieving input in the Car Payment Calculator application.

 2009 Pearson Education, Inc. All rights reserved.


30
Declaring Variables and Retrieving
User Input (Cont.)

■ The application computes the amount of the loan by


subtracting the down payment from the price.
■ These calculations need to occur only once, so they
are placed before the Do While...Loop statement
(Fig. 9.12).

Figure 9.12 | Determining amount borrowed and monthly interest rate.

 2009 Pearson Education, Inc. All rights reserved.


31
Calculating the Monthly Payment Amounts with
a Do While...Loop Repetition Statement

■ After you type line 33 and press Enter, the IDE will
close the repetition statement by adding the keyword
Loop in line 35 (Fig. 9.13).

Figure 9.13 | Loop-continuation condition.

 2009 Pearson Education, Inc. All rights reserved.


32
Calculating the Monthly Payment Amounts with
a Do While...Loop Repetition Statement (Cont.)

■ This loop is an example of counter-controlled


repetition.
– 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.

 2009 Pearson Education, Inc. All rights reserved.


33
Calculating the Monthly Payment Amounts with
a Do While...Loop Repetition Statement (Cont.)

■ The number of months changes with each iteration of


this loop, and the calculation result changes based on
the length of the payment period (Fig. 9.14).

Figure 9.14 | Converting the loan duration from years to months.

 2009 Pearson Education, Inc. All rights reserved.


34
Calculating the Monthly Payment Amounts with
a Do While...Loop Repetition Statement (Cont.)

■ The Pmt function returns a Double value that specifies


the monthly payment amount on a loan for a constant
interest rate and a given time period (Fig. 9.15).
■ Borrowed amounts are represented by negative
values.

Figure 9.15 | Pmt function returns monthly payment.

 2009 Pearson Education, Inc. All rights reserved.


35
Calculating the Monthly Payment Amounts with
a Do While...Loop Repetition Statement (Cont.)

■ The number of monthly payments and the monthly


payment amounts are displayed beneath the header
in the ListBox.
■ String.Format is used to display
monthlyPayment in currency format (Fig. 9.16).

Figure 9.16 | Displaying the number of months and the amount of each monthly
payment.

 2009 Pearson Education, Inc. All rights reserved.


36
Calculating the Monthly Payment Amounts with
a Do While...Loop Repetition Statement (Cont.)

■ The counter variable years is incremented in each


iteration until it equals 6 (Fig. 9.17).
■ Then the loop-continuation condition (years <= 5)
evaluates to False and the repetition ends.

Figure 9.17 | Incrementing the counter.

 2009 Pearson Education, Inc. All rights reserved.


37
Outline

■ Figure 9.18 presents the source code for the application.


(1 of 3 )
1 Public Class CarPaymentCalculatorForm
2 ' handles Calculate Button's Click event
3 Private Sub calculateButton_Click(ByVal sender As System.Object, _
4 ByVal e As System.EventArgs) Handles calculateButton.Click
5
6 Dim years As Integer = 2 ' repetition counter
7 Dim months As Integer = 0 ' payment period
8 Dim price As Decimal = 0 ' car price
9 Dim downPayment As Decimal = 0 ' down payment
10 Dim interest As Double = 0 ' interest rate
11 Dim monthlyPayment As Decimal = 0 ' monthly payment
12 Dim loanAmount As Decimal = 0 ' cost after down payment
13 Dim monthlyInterest As Double = 0 ' monthly interest rate
14
15 ' remove text displayed in ListBox
16 paymentsListBox.Items.Clear() Clear the ListBox

 2009 Pearson Education,


Inc. All rights reserved.
38
Outline

(2 of 3 )
17
18 ' add header to ListBox
19 paymentsListBox.Items.Add("Months" & ControlChars.Tab & _
20 ControlChars.Tab & "Monthly Payments") Add a header to the ListBox
21
22 ' retrieve user input and assign values
23 ' to their respective variables
24 downPayment = Val(downPaymentTextBox.Text)
25 price = Val(priceTextBox.Text)
26 interest = Val(interestTextBox.Text) / 100
27
28 ' determine amount borrowed and monthly interest rate
29 loanAmount = price - downPayment
30 monthlyInterest = interest / 12
31

 2009 Pearson Education,


Inc. All rights reserved.
39
Outline

(3 of 3 )
32 ' calculate payments for two, three, four and five year loans
33 Do While years <= 5 Do While...Loop repeats its
34 ' calculate payment period body while years is less than or
35 months = 12 * years equal to 5
36
37 ' calculate monthly payment using Pmt Calculate term in months
38 monthlyPayment = _
39 Pmt(monthlyInterest, months, -loanAmount) Calculate monthly
40 payment amount
41 ' display payment value
42 paymentsListBox.Items.Add(months & ControlChars.Tab & _
43 ControlChars.Tab & String.Format("{0:C}", _
44 monthlyPayment)) Display number of months
and monthly payment
45
amount
46 years += 1 ' increment counter
47 Loop Increment counter years so
48 End Sub ' calculateButton_Click the loop-continuation
49 End Class ' CarPaymentCalculatorForm condition eventually becomes
false

 2009 Pearson Education,


Inc. All rights reserved.

You might also like