CPP Program to Find the Sum of variables using a Function with Default Arguments

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:

  1. Start the program.
  2. Declare the variables and functions.
  3. Give the values for two arguments in the function declaration itself.
  4. Call function sum () with three values such that it takes one default arguments.
  5. Call function sum () with two values such that it takes two default arguments.
  6. Call function sum() with one values such that it takes three default arguments
  7. Inside the function sum (), calculate the total.
  8. Return the value to the main () function.
  9. 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.

Leave a Comment