# Simple Interest Program in C++ using Class

## Introduction

In this post, I am going to write a simple interest program in c++ using class. This program will read three values i.e. principal amount, the number of years and rate of interest. After reading these values, we will calculate simple interest using the following formula.

``Simple Interest = (p * n * r) / 100``

In the above formula, p is nothing but the principal amount, n is the number of years and r is the rate of interest. These are our inputs in this program. Now, see the following program.

### Simple Interest Program in C++ using Class

``````//Simple Interest Program in C++ using Class
#include<iostream>
using namespace std;
class simple
{
int p,n;
float r,si;
public:
void getvalues()
{
cout<<"Enter Principal amount\n";
cin>>p;
cout<<"Enter Number of Years\n";
cin>>n;
cout<<"Enter Rate of Interest\n";
cin>>r;
}
void display()
{
si=(p*n*r)/100;
cout<<"Simple Interest = "<<si<<endl;
}
};
int main()
{
simple s;
s.getvalues();
s.display();
return 0;
}
``````

As you can see, in the above program, we have defined two member functions i.e. getvalues() and display(). In the getvalues() function, we are reading the values of p, n and r. In the display() function, we are calculating the simple interest and displaying the result.

See the following output.

### Output

``````Enter Principal amount
1000
Enter Number of Years
18
Enter Rate of Interest
7.5
Simple Interest = 1350``````

This is the simple interest program in c++ using class. We can write the same program using the constructor.

Simple Interest Program in C++ using Constructor

We are modifying the above c++ program. Instead of getvalues(), we have used constructor. The advantage of using constructor is that there is no need to call it. It will automatically get invoked when object of this class is created.

See the following program.

``````//Simple Interest Program in C++ using Class
#include<iostream>
using namespace std;
class simple
{
int p,n;
float r,si;
public:
simple()   // constructor
{
cout<<"Enter Principal amount\n";
cin>>p;
cout<<"Enter Number of Years\n";
cin>>n;
cout<<"Enter Rate of Interest\n";
cin>>r;
}
void display()
{
si=(p*n*r)/100;
cout<<"Simple Interest = "<<si<<endl;
}
};
int main()
{
simple s;
s.display();
return 0;
}
``````

Output of this program remains the same as the first program.

I hope, you have understood these programs. If you have any difficulties, then please, feel free to contact me.

Thank you.