C++ program to calculate the simple interest using class

Learn, how can we find the calculate simple interest using the class and object approach?
Submitted by Shubh Pachori, on September 04, 2022

Example:

Input:
Enter Principle: 1000
Enter Rate: 2
Enter Time: 1

Output:
Simple Interest: 20
Total Amount: 1020

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

#include <iostream>
using namespace std;

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

  // public member functions
 public:
  // putValues() function to insert values like
  // principle, rate and time
  void putValues() {
    cout << "Enter Principle: ";
    cin >> principle;

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

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

  // getSimpleInterest() function to calculate
  // Simple Interest and Total Amount
  void getSimpleInterest() {
    // initializing float type variables 
    // to perform operations
    float interest, amount;

    // calculating simple interest
    interest = (principle * rate * time_period) / 100;

    // calculating Total Amount
    amount = interest + principle;

    cout << "Simple Interest: " << interest << endl;

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

int main() {
  // create object
  SimpleInterest S;

  // calling putValues() function 
  // to insert values
  S.putValues();

  // calling getSimpleInterest() function to
  // calculating simple interest
  S.getSimpleInterest();

  return 0;
}

Output:

Enter Principle: 12000
Enter Rate: 12
Enter Time: 2
Simple Interest: 2880
Total Amount: 14880

Explanation:

In the above code, we have created a class SimpleInterest, 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 getSimpleInterest() to store values and to calculate simple interest and total amount.

In the main() function, we are creating an object S of class SimpleInterest, reading the values inputted by the user using putValues() function, and finally calling the getSimpleInterest() member function to calculate the simple interest and total amount. The getSimpleInterest() function contains the logic to calculate the simple 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.