Function to calculate compound interest in C++

To calculate compound interest in C++, you can create a function that takes in the principal amount, interest rate, time period, and the number of times interest is compounded per year as parameters. Here's an example of a function that calculates compound interest:

#include <iostream>
#include <cmath>

double calculateCompoundInterest(double principal, double rate, double time, int compoundFrequency) {
    double amount = principal  pow(1 + (rate / compoundFrequency), compoundFrequency  time);
    double compoundInterest = amount - principal;

    return compoundInterest;
}

int main() {
    double principal, rate, time;
    int compoundFrequency;

    std::cout << "Enter the principal amount: ";
    std::cin >> principal;

    std::cout << "Enter the interest rate (in decimal form): ";
    std::cin >> rate;

    std::cout << "Enter the time period (in years): ";
    std::cin >> time;

    std::cout << "Enter the number of times interest is compounded per year: ";
    std::cin >> compoundFrequency;

    double interest = calculateCompoundInterest(principal, rate, time, compoundFrequency);

    std::cout << "The compound interest is: " << interest << std::endl;

    return 0;
}

Explanation:

  1. The function calculateCompoundInterest is defined with four parameters: principal, rate, time, and compoundFrequency. These parameters represent the principal amount, interest rate, time period, and the number of times interest is compounded per year, respectively.

  2. The variable amount is calculated using the formula A = P (1 + (R / N))^(N T), where A is the amount, P is the principal, R is the rate, N is the compound frequency, and T is the time period.

  3. The variable compoundInterest is calculated by subtracting the principal amount from the amount.

  4. The function returns the value of compoundInterest.

  5. In the main function, the user is prompted to enter the principal amount, interest rate, time period, and the number of times interest is compounded per year.

  6. The calculateCompoundInterest function is called with the provided inputs, and the result is stored in the variable interest.

  7. The compound interest is then displayed to the user.