86.1k views
3 votes
Write separately prototype and definition for function sum that can be used as shown (it adds its arguments and returns the summation, and it can be called with 1 arguments as well just returning the argument itself). Do it with default parameters.

1 Answer

6 votes

Final answer:

To write a sum function with default parameters that can be called with one or two arguments, first declare the prototype then define the function. The prototype specifies a default parameter, while the function definition handles the addition, enabling the function to return the sum of its arguments or the single argument if only one is provided.

Step-by-step explanation:

To write separately prototype and definition for function sum with default parameters in a programming language such as C++, follow these steps:

Prototype

First, you'll need to declare the function prototype. For a sum function that can handle default parameters, ensuring that it can be called with a single argument, you would write something like this:

int sum(int a, int b = 0);

Definition

Then, you'll define the function itself, implementing the logic to add the arguments:

int sum(int a, int b) {
return a + b;
}

If you call this function sum with one argument, the second argument will default to zero, effectively just returning the single argument. If you provide two arguments, it will return their summation.

Remember that this implementation assumes the function will be used in an environment that supports default parameters, like C++.

User MadsVJ
by
7.9k points