The mortgage program extends the payment program example presented in the previous chapter. Review the comments in payment.cpp before proceeding with this extended version. The mortgage program calculates a monthly mortgage payment based on the principal (i.e., the amount borrowed), the annual percentage rate (APR), and the loan duration in years. It then prints a complete amortization table that lists each payment:
The payment number
The balance after the payment
The amount of the payment applied to the balance
The amount of the payment applied to interest
Test Cases
P
R
N
payment
Case 1
100000
8% = 0.08
30
733.76
Case 2
100000
4% = 0.04
15
739.69
Program Listing
Output
Using the first test case, the for loop produces 360 output lines, which scroll off the console window. Depending on how you run the program, 360 lines of output may also be too many lines to allow you to scroll back to the top. If we run the program from a command line prompt, it is possible to redirect the output to a file:
C:\>mortgage > amortization.txt
Used this way, > is called the file redirection operator. We can imagine the redirection operator acting like a funnel, catching the program's output and funneling or sending it to a file. If amortization.txt doesn't exist, the operation creates and fills it with the program's output; if the file exists, the operation discards its previous contents before filling it.
However, if the program uses cout for all output operations, the redirection operator redirects all output to the file, including the three prompts at the beginning of the program. In that case, the user doesn't see the prompts and doesn't know the program is waiting for input. We solve the problem by separating the output into two streams: one stream (the payment, table, and totals) is sent to cout and is redirected to the file. However, the program sends the prompts cerr. The file redirection operator only redirects cout to the file, so the prompts, sent to cerr, still display on the console.