9. Control Structures

9.4. Example: Car Loan

Recall the self-study exercise from Chapter 5 that calculated the value of a bank CD (a) given its initial principle (p), interest rate (r), and number of years (n), using the formula a = p(1 + r)n. This section explains how to use

 

SECTION 6.4 Example: Car Loan253

the same formula to calculate the cost of a car loan for different interest rates over various time periods.

Problem Description

For example, suppose you are planning on buying a car that costs $20,000. You find that you can get a car loan ranging anywhere from 8 to 11 percent, and you can have the loan for periods as short as two years and as long as eight years. Let’s use our loop constructs to create a table to show what the car will actually cost you, including financing. In this case, a will represent the total cost of the car, including the financing, and p will represent the price tag on the car ($20,000):

 

 

 

 

 

 

 

\J

Algorithm Design

The key element in this program is the nested for loop that generates the

table. Because the table contains seven rows, the outer loop should iterateNested loop design

seven times, through the values 2, 3,8:

,,

 

J

The inner loop should iterate through each of the interest rates, 8 through 11:

,,

 

 

 

J

The financing calculation should be placed in the body of the inner loop together with a statement to print one cell (not row) of the table. Suppose the variable we use for a in the formula is carPriceWithLoan, and the variable we use for the actual price of the car is carPrice. Then our inner loop body is

,,

 

 

J

Note that the rate is divided by both 100.0 (to make it a percentage) and by

365.0 (for daily compounding), and the year is multiplied by 365.0 before these values are passed to the Math.pow() method. It is important here

 

 

 

 

 

 

 

Formatting output


to use 100.0 and not 100 so that the resulting value is a double and not the int 0.

Implementation

The program must also contain statements to print the row and column headings. Printing the row headings should be done within the outer loop, because it must be done for each row. Printing the column head- ings should be done before the outer loop is entered. Finally, our program should contain code to format the dollar and cents values properly. For this we use the java.text.NumberFormat class that was described in Chapter 5. The complete program is shown in Figure 6.3.

 

,,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

J

Figure 6.3: The CarLoan application.