Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
Problem Statement - Simple interest program with function.
Write a c++ program to define a function si(p,r,t) with input parameters as p, r and t for principal, rate and term and let it return no data. The calculated value of interest may be saved in a global variable.
Also show the demonstration of working of this function by calling it in the main() routine by passing some fixed values of p,r and t. In the main routine print the final amount by adding the interest to the principal amount.
Solution
TC++ #2386
Run Output
Final amount=1300
void si(float,float,float); //Function prototype float interest; //Global variable to save calculated value of interest from the function
float p=1000,r=10,t=3; //Fixed value of p,r,t kept in main
si(p,r,t); //function called with actual parameters.
cout<<“Final amount=”<<p+interest<<endl;
The global value which is expected to be filled with interest is added to principal to print the final amount.
void si(float p,float r, float t)
This is the function definition header with void return type as nothing is returned from the function. all three arguments are of float data type.
{ interest = p*r*t/100; //interest formula is applied and output is saved in the global variable interest. }
Notes
Generally such functions return the value of calculated figure.Here we are just demonstrating the use of global variables setting using function.
Common Errors
Some time students attempt this function with int value of p, r, and t. In that case the interest formula should be carefully written as float intrest = 0.01 *p *r*t or as float interest=(float (1)/100)*p*r*t. This is important to avoid integer division by hundred. Else the calculation of 1/100 may return 0.