Aim:
To write a C++ program to find the sum for the given variables using function with default arguments.
Default Arguments in C++
- A default argument is a function argument that has a default value provided to it.
- If the user does not supply a value for this argument, the default value will be used.
- If the user does supply a value for the default argument, the user-supplied value is used.
Note: Only the trailing arguments can have default values and therefore we must add default values form right-to-left.
Some examples of function declaration with default values are:
int Add(int x, int y, int z=30); | //Valid |
int Add(int x, int y=20, int z=30); | //Valid |
int Add(int x=10, int y=20, int z=30); | //Valid |
int Add(int x=10, int y, int z); | //Invalid |
int Add(int x=10, int y, int z=30); | //Invalid |
Algorithm:
- Start the program.
- Declare the variables and functions.
- Give the values for two arguments in the function declaration itself.
- Call function sum () with three values such that it takes one default arguments.
- Call function sum () with two values such that it takes two default arguments.
- Call function sum() with one values such that it takes three default arguments
- Inside the function sum (), calculate the total.
- Return the value to the main () function.
- Display the result.
Program:
#include<iostream> using namespace std; int addof4numbers(int a,int b,int c=15,int d=10) { return a+b+c+d; } int main() { cout<<"add of four numbers :"<<addof4numbers(3,8)<<endl; cout<<"add of four numbers :"<<addof4numbers(3,8,8)<<endl; cout<<"add of four numbers :"<<addof4numbers(3,8,5,2)<<endl; cout<<"add of four numbers :"<<addof4numbers(3,8)<<endl; return 0; }
Output:
add of four numbers :36 add of four numbers :29 add of four numbers :18 add of four numbers :36
Result:
Thus, Implement using Functions with Default Arguments was executed successfully.