Section 4 - The Mortgage Calculator

5A.4.1 The Program Listing

Now we can look at the full program.  You can copy/paste this into your C++ IDE and try it out.    As I said,  the definition of each of the three methods appears right after the main().

Here is the listing.  See how much you can understand before reading on.

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

// method prototypes
void stateInstructions();
void getInputAndComputeMonthlyPayment();
void sayGoodbye();

int main()
{
stateInstructions();
getInputAndComputeMonthlyPayment();
sayGoodbye();
}

// gives an overview to user
void stateInstructions()
{
string instructions;

instructions =
"\nThe following program will calculate the \n"
"monthly payment  required for a loan of D dollars \n"
"over a period of Y years at an annual \n"
"interest rate of R%.\n";
cout << instructions;
}

// does all the work - gets input, computes and reports answer
void getInputAndComputeMonthlyPayment()
{
string prompt;
double dblPrincipal, dblRate, dblYears, dblMoRt, dblMonths;
double dblTemp, dblPmt;

// get principal
prompt = "\nEnter amount of the loan. (only use numbers, \n"
"please, no commas or characters like '$')\n"
"Your loan amount: ";
cout << prompt;
cin >> dblPrincipal;

// get interest
prompt = "\nNow enter the interest rate (If the quoted rate is 6.5%, \n"
"for example, enter 6.5 without the %.)\n"
"Your annual interest rate: ";
cout << prompt;
cin >> dblRate;

// get length of loan
prompt = "\nEnter term of the loan in years: ";
cout << prompt;
cin >> dblYears;

// convert years to months
dblMonths = dblYears * 12;

// convert rate to decimal and months
dblMoRt = dblRate / (100 * 12);

// use formula to get result
dblTemp = pow(1 + dblMoRt, dblMonths);
dblPmt = dblPrincipal * dblMoRt * dblTemp
/ ( dblTemp - 1 );

cout <<  "\nYour Monthly Payment: " << dblPmt << endl;
}

// sign off
void sayGoodbye()
{
string signoff;
signoff =
"\nThanks for using the Foothill Mortgage Calculator. \n"
"We hope you'll come back and see us again, soon.\n\n";
cout << signoff;
}

5A.4.2 Discussion of the Program

We already discussed what stateInstructions() does.  You can see that sayGoodbye() works exactly the same way, but with a different phrase to send to the screen.  That leaves the method getInputAndComputeMonthlyPayment() to discuss.

That's all I can think to say about this program.  You should meditate on these comments as you run the program and examine its source.  You might try changing the wording around but you'll have to keep the math as is if you want it to be accurate. While you're at it, you can see if you can afford that home you want.