Default Arguments in Function

Default Arguments in Function

Medium C++ Functions 40 views
Explanation Complexity

Problem Statement

Create function with default parameter values.
Real Life: Like having default settings that can be changed if needed.

Input Format

No user input.
Function is called with and without arguments.

Output Format

Result printed using default and user-provided values.

Example

Call function without argument
Call function with argument = 5
Value = 10
Value = 5

Constraints

• Default value must be given in function declaration

• Function parameters must be from right to left

Concept Explanation

A default parameter is a value used by the function when no argument is passed.
It works like default settings that can be changed when needed.

Step-by-Step Explanation

1.Declare a function with a parameter having a default value (example: int x = 10).

2.If the function is called without argument:

• Default value is used.

3.If the function is called with argument:

• Passed value overrides the default value.

4.Function executes normally in both cases.

5.Print the value used inside the function.

Concept Explanation

A default parameter is a value used by the function when no argument is passed.
It works like default settings that can be changed when needed.

Step-by-Step Explanation

1.Declare a function with a parameter having a default value (example: int x = 10).

2.If the function is called without argument:

• Default value is used.

3.If the function is called with argument:

• Passed value overrides the default value.

4.Function executes normally in both cases.

5.Print the value used inside the function.

Input / Output Format

Input Format
No user input.
Function is called with and without arguments.
Output Format
Result printed using default and user-provided values.
Constraints
• Default value must be given in function declaration

• Function parameters must be from right to left

Examples

Input:
Call function without argument Call function with argument = 5
Output:
Value = 10 Value = 5

Example Solution (Public)

C++
int multiply(int a, int b = 2) {  // b has default value 2
    return a * b;
}

void function_q10_default_args() {
    cout << "10 * 2 (default): " << multiply(10) << endl;
    cout << "10 * 5 (custom): " << multiply(10, 5) << endl;
}

Official Solution Code

int multiply(int a, int b = 2) {  // b has default value 2
    return a * b;
}

void function_q10_default_args() {
    cout << "10 * 2 (default): " << multiply(10) << endl;
    cout << "10 * 5 (custom): " << multiply(10, 5) << endl;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.