C Program to Calculate Compound Interest

Building a financial calculator is a great way to learn about the math.h library and how to handle exponential calculations in C programming.

Concept Overview

Compound interest is calculated using the following formula:

  • Total Amount (A) = $P(1 + R/100)^T$
  • Compound Interest (CI) = Total Amount - Principal

Program Implementation

C
#include <stdio.h>
#include <math.h>

int main() {
    float principal, rate, time;
    double compoundInterest, totalAmount;

    printf("Enter Principal amount: ");
    scanf("%f", &principal);

    printf("Enter Annual Interest Rate (%%): ");
    scanf("%f", &rate);

    printf("Enter Time Period (years): ");
    scanf("%f", &time);

    // Calculating Total Amount: A = P * (1 + R/100)^T
    totalAmount = principal * pow((1 + (rate / 100.0)), time);
    
    // Calculating Compound Interest
    compoundInterest = totalAmount - principal;

    printf("\n--- Financial Summary ---\n");
    printf("Total Amount: %.2f\n", totalAmount);
    printf("Compound Interest: %.2f\n", compoundInterest);

    return 0;
}

Sample Output

Enter Principal amount: 5000
Enter Annual Interest Rate (%): 10
Enter Time Period (years): 2

--- Financial Summary ---
Total Amount: 6050.00
Compound Interest: 1050.00

Key Takeaways

  • The math.h header file is required to use the pow() function.
  • We use 100.0 instead of 100 to ensure floating-point division; otherwise, the result might be truncated to zero.
  • The double data type is used for the results to ensure higher precision for financial calculations.
  • The pow(base, exponent) function is used to calculate the exponential part of the formula.
Note: Note: When compiling on some Linux systems, you may need to link the math library using the -lm flag, like so: gcc program.c -lm.