How to calculate compound interest in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>  // For std::pow
#include <iomanip> // For std::setprecision

// Function to calculate compound interest
double calculateCompoundInterest(double principal, double rate, double years) {
    if (principal < 0 || rate < 0 || years < 0) {
        std::cerr << "Error: Principal, rate, and years must be non-negative values.\n";
        return -1;
    }

    // Calculate total amount using the compound interest formula
    double amount = principal * std::pow((1 + rate / 100), years);

    // Return compound interest
    return amount - principal;
}

int main() {
    double principal = 100000;
    double rate = 3.5;
    double years = 5;

    double compoundInterest = calculateCompoundInterest(principal, rate, years);

    std::cout << std::fixed << std::setprecision(2);
    std::cout << "Principal Amount: " << principal << "\n";
    std::cout << "Annual Interest Rate: " << rate << "%\n";
    std::cout << "Years: " << years << "\n";
    std::cout << "Compound Interest: " << compoundInterest << "\n";
    std::cout << "Total Amount: " << principal + compoundInterest << "\n";
}



/*
run:
    
Principal Amount: 100000.00
Annual Interest Rate: 3.50%
Years: 5.00
Compound Interest: 18768.63
Total Amount: 118768.63
    
*/

 



answered Aug 30, 2025 by avibootz

Related questions

...