Function in function calls using salary preparation example
Using the example of salary preparation for building related functions and using function in function calls.
Learning Objectives
- Learning the case of function in function calls.
- Learning to use global variables when many functions are involved.
- Learning to return correct data type using functions with properly formed casting.
- Learning to make modular programs.
Source Code
|
|
Run Output
Code Understanding
int da=30,hra=12,pf=10,tax=15;
These value can be used by many functions so they have been declared as global variables.
float sal2give(int); float salary(int); float amt(int,int);
These are function prototypes of different functions.
do{
cout<<“Give Basic :”;cin>>basic;
cout<<“Salary to give =”<<sal2give(basic)<<endl;
}while(basic != 0);
Here we use this do-while loop so that input of basic can be taken for many users and salary can be prepared. This makes the program to be used for practical application. The program terminates when the value of basic is put as 0.
float sal2give(int basic)
{
float s2g=salary(basic)-amt(basic,pf)-amt(basic,tax);
return s2g;
}
This function returns the final value of salary to give. This in turn calls other functions salary() 1 time and the amt() function two times to get right values returned from the external methods and then use it for calculation here.
float salary(int basic)
{
float sal=basic+amt(basic,da)+amt(basic,hra);
return sal;
}
This function takes basic as its input and calls another function amt(). The call to amt() function is done with suitable input of globally set percentage values of da and hrs.
float amt(int b,int p)
{
return b*(float (p)/100);
}
This is basically a percentage based amount calculator. Its specialty is that it can collect the input data in integer variables and return the calculated amount in float with proper casting where ever required in its calculation. For this reason its return type is float.
Notes
- This is a typical example of modular programming using functions.
- This example uses global variables. More sophisticated examples will avoid global variables in favour of class based variables. This way of usage was traditionally being in done in C programming.
Suggested Filename(s): fif-salary.cpp
Created: 8-Jan-2018 23:03 | Updated: 15-Sep-2018 14:11|
