Section 2 - Mortgage Calculator Version 3
5B.2.1 The Program Listing
This latest version of the mortgage calculator demonstrates the use of global variables:
#include <iostream> #include <string> #include <cmath> using namespace std; // method prototypes void stateInstructions(); void getInput(); double computeMonthlyPayment(); void sayGoodbye(); // global variables shared by more than one method double dblPrincipal, dblRate, dblYears; int main() { double answer; stateInstructions(); getInput(); answer = computeMonthlyPayment(); cout << "\nYour Monthly Payment: " << answer << endl; 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; } // gets input, stores in globals void getInput() { string prompt; // 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; } // computes and returns answer double computeMonthlyPayment() { double dblTemp, dblPmt, dblMoRt, dblMonths; // 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 ); // now that we have computed the payment, return it return dblPmt; } // 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; }
Notice that getInput() is using only one local object, prompt. Other than that, it is using the global variables (of course, without declaring them).
If you define a global variable, you are not going to define it again within a method. Why? If you did, you would "hide" the global variable from that method and create a new, local variable only known to the method. The same is true in other areas of C++ that have a nested structure (like blocks within methods or methods within classes, things we will get to later). If you declare a variable in an inner structure that has the same name as one in a larger, outer structure, you will be rendering the outer data unreachable. This abstract notion is only understandable to you now in terms of the outer globals and the inner locals.
Sometimes we see methods that have no local variables defined at the top because they are going to use only global variables.