In: Computer Science
Write a loan amortization program in C++. Assume the loan is paid off in equal monthly installments. To compute the monthly payment you must know: 1.the initial loan value 2. # of months the loan is in effect 3. APR. You should prompt the user for each of these 3 things then compute the monthly payment. The following formula is useful: Payment = (factor * value * monthly_rate) / (factor - 1) where factor = (1 + monthly_rate) ^ number_of_months. Then set up the amortization table that will show for each month the starting balance, the interest paid, the payment amount and the new balance. Use comments in the program and use a function that compute_payment given 3 values of loan amount, APR, and loan length. Most variables in the program should be doubles. The output should have headers for each column, echo the input values, and must be aligned.
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<iomanip>
using namespace std;
// emi formula
double compute_payment(double amount,double rate,int month){
double factor=pow(1+rate/1200.0,month);
return((factor*amount*(rate/1200.0))/(factor-1));
}
int main(){
double loan,interestRate;
int month;
// enter user loan amount
cout << "Loan Amount: ";
cin >> loan;
// enter interest rate
while(true){
cout << "Interest Rate (% per
year): ";
cin >> interestRate;
if(interestRate>0)
{
break;
}
// if interest rate -ve
else{
cout<<"Interest rate must be positive.\n";
}
}
// enter number of months
while(true){
cout << "Number of months:
";
cin >> month;
if(month>0){
break;
}
// if months are -ve
else{
cout<<"Month must be positive.\n";
}
}
double
monthlyPaid=compute_payment(loan,interestRate,month);
// display EMI
cout<<"\nEMI amount is
$"<<monthlyPaid;
cout <<
"\n\n*****************************************************************\n"
<< "\t\t\tAmortization Table\n"
<<
"*****************************************************************\n"
<<
"Month\tBalance\t\tPayment\t\tRate\tInterest\tPrincipal\n";
// intially current month is 0
int currentMonth=0;
double interestTotal=0;
while (loan > 0.01) {
if (currentMonth == 0) {
cout <<
currentMonth++ <<
"\t$"<<left<<fixed<<setw(12)<<setprecision(2)<<
loan;
cout <<
"\n";
}
else {
cout<<currentMonth++ <<"\t$";
// calculate
interest amount
double
interestAmt=loan*(interestRate/1200.0);
// add
interest
interestTotal+=interestAmt;
// sunbtract
principal from loan amount
loan-=(monthlyPaid-interestAmt);
cout<<left<<fixed<<setw(15)<<setprecision(2)<<loan;
// display
monthly payment
cout<<"$";
cout<<left<<fixed<<setw(15)<<setprecision(2)<<monthlyPaid;
// disaply
interest rate
cout<<left<<fixed<<setw(12)<<setprecision(2)<<interestRate<<"$";
// display
interest amount
cout<<left<<fixed<<setw(12)<<setprecision(2)<<interestAmt<<"$";
// display
principal
cout<<left<<fixed<<setw(12)<<setprecision(2)<<(monthlyPaid-interestAmt)<<"\n";
}
}
system("pause");
return 0;
}