C++ Default Arguments

Default Arguments are those arguments for which we provide default values in the function declaration. A function with default arguments can be called without specifying all or some argument's value.

Default arguments are useful in situations where one or more argument value is constant or fixed like interest rate, pi etc. Default argument must be declared from right to left.

Declaration of default argument:

int fun(int i, int j, int k=5); //default argument declaration

a=fun(10,10,10); //Assign 10 in i, j & k
a=fun(10,10); //Assign i=10, j=10 and k=5

Example 1: WAP to calculate simple interest using function with default argument.


float si(float p,  float t, float r=10.5); //default argument declaration

void main()
    float p,r,t,s;
    cout<<"Enter Principal: ";
    cout<<"Enter Rate: ";
    cout<<"Enter Time: ";
    cout<<endl<<"Simple interest with default argument is: "<<s;
    cout<<endl<<"Simple interest without default argument is: "<<s;
float si(float p, float r, float t)
    float a = p*r*t/100;
    return a;
Enter Principal: 1000
Enter Rate: 5
Enter Time: 10
Simple interest with default argument is: 500
Simple interest without default argument is: 1050

Exercise 1: Find sum of numbers using default argument, argument can be passed between 2 and 5.

Exercise 2: Find Power (a, b), using default arguments, if 2nd argument is omitted, then calculate square of a.