Calculate Compound Interest in C++
Compound interest in C++ with pow. ^ is XOR, not exponent.
1#include <iostream>2#include <iomanip>3#include <cmath>4using namespace std;56int main() {7 float principal, rate, time, amount, interest;89 cout << "Enter principal amount: ";10 cin >> principal;1112 cout << "Enter rate of interest (per year): ";13 cin >> rate;1415 cout << "Enter time (in years): ";16 cin >> time;1718 // Compound Interest: A = P(1 + R/100)^T19 amount = principal * pow((1 + rate / 100), time);20 interest = amount - principal;2122 cout << fixed << setprecision(2);23 cout << "Compound Interest = " << interest << endl;24 cout << "Total Amount = " << amount << endl;2526 return 0;27}
Output
Enter principal amount: 10000 Enter rate of interest (per year): 5 Enter time (in years): 2 Compound Interest = 1025.00 Total Amount = 11025.00
What's going on
Compound interest in C++ uses a power: A = P * (1 + R/100)^T. Simple interest is just a multiply. Same inputs as the previous program, different formula.
#include <cmath>
Required for pow. Skip it and pow is an unknown name.
#include <iomanip>
fixed and setprecision(2), same as simple interest.
float principal, rate, time, amount, interest;
Five variables. amount is the future value. interest is what you earned.
amount = principal * pow((1 + rate / 100), time);
Sample: 10000 * (1.05)^2 = 11025. pow takes two doubles; float promotes.
^ is XOR, not exponent. 2 ^ 3 is 1. Don't write (1 + rate/100)^time expecting a power.
interest = amount - principal;
11025 - 10000 = 1025. Printing only amount makes it look like the interest is the whole pile.
Simple interest on the same numbers was 1000. Compound is 1025 because the second year earns interest on 10500, not on 10000.
Some textbooks compound n times per year: P * pow(1 + R/(100*n), n*T). This program uses yearly compounding. Read the formula in the code.