C++ program to calculate the compound interest using class

Given values, we have to calculate the compound interest using the class and object approach.
Submitted by Shubh Pachori, on September 04, 2022

Example:

Input:
Enter Principle: 10000
Enter Rate: 5
Enter Time: 2

Output:
Compound Interest: 1025
Total Amount: 11025

C++ code to calculate the compound interest using the class and object approach

#include <math.h>
#include <iostream>
using namespace std;

// create a class
class CompoundInterest {
  // private data members
 private:
  float principle, rate, time_period;

  // public member functions
 public:
  // putValues() function to input values
  void putValues() {
    cout << "Enter Principle: ";
    cin >> principle;

    cout << "Enter Rate: ";
    cin >> rate;

    cout << "Enter Time: ";
    cin >> time_period;
  }

  // getCompoundInterest() function to calculate 
  // compound_interest and total amount
  void getCompoundInterest() {
    // initializing float type variables 
    // to perform operations
    float compound_interest, amount;

    // calculating compound_interest
    compound_interest =
        principle * pow((1 + rate / 100), time_period) - principle;

    // calculating Total Amount
    amount = principle * pow((1 + rate / 100), time_period);

    cout << "Compound Interest: " << compound_interest << endl;

    cout << "Total Amount: " << amount << endl;
  }
};

int main() {
  // create object
  CompoundInterest C;

  // calling putValues() function to 
  // input values
  C.putValues();

  // calling getCompoundInterest() function to 
  // calculate Compound Interest and Total Amount
  C.getCompoundInterest();

  return 0;
}

Output:

Enter Principle: 11999
Enter Rate: 3
Enter Time: 5
Compound Interest: 1911.13
Total Amount: 13910.1

Explanation:

In the above code, we have created a class CompoundInterest, three float type data members principle, rate and time_period to store the values like principle, rate and time, and public member functions putValues() and getCompoundInterest() to store values and to calculate compound interest and total amount.

In the main() function, we are creating an object C of class CompoundInterest, reading the values inputted by the user using putValues() function, and finally calling the getCompoundInterest() member function to calculate the compound interest and total amount. The getCompoundInterest() function contains the logic to calculate the compound interest and total amount and printing the result.

C++ Class and Object Programs (Set 2) »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.