WAP to calculate simple interest using default argument for rate = 20%
SIMPLE INTEREST = PRINCIPLE*TIME*RATE;
Objective
Write a C++ program to calculate Simple Interest using Default Arguments.
Algorithm / Approach
- Define a function
sim(int p, int t, int r = 20). - Inside the function, calculate
si = p * r * t / 100. - In
main(), call the function normally with 3 arguments:i.sim(1000, 3, 10). - Call the function again with only 2 arguments:
i.sim(1000, 3).
main.cpp
#include<iostream>
using namespace std;
class Interest {
public:
void sim(int p,int t, int r = 20) {
double si = p*r*t/100;
cout<<"Simple Interest = "<< si;
cout<< endl;
}
};
int main() {
Interest i ;
i.sim(1000,3,10);
i.sim(1000,3);
return 0;
}
Expected Output
Simple Interest = 300 Simple Interest = 600
Explanation of the Program
- Default arguments allow you to make parameters optional when calling a function.
- If you provide all 3 arguments (e.g., rate = 10), it uses your provided rate. But if you omit the last argument, C++ automatically falls back to the default value you defined (rate = 20) instead of throwing an error.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)