The function given below takes a number "n" as the input and calculates the sum of first "n" natural
numbers. Which statement should be inserted in place of "??" to get the required output?
function sum(n)
{
if (??)
return 1
else
return (n + sum(n-1))
end
}
Answers
Answer:
??= 0
Step-by-step explanation:
natural numbers start from 1. so if input provided is 0, 1 may be returned.
Answer:
n=1
Step-by-step explanation:
Concept= IF ELSE iteration
Given= A function for sum of n natural numbers.
To Find= The missing statement of the function given.
Explanation=
We have been the function as
sum(n)
{
if (??)
return 1
else
return (n + sum(n-1))
}
This function calculates the sum of first n natural numbers.
We have to replace the "??" with the desired statement so that the function may work to calculate the sum on entering the value of n.
This statement returns the value to the function.
This is calculating sum as when the digit n is entered the sum is calculated as 1+2+3+4+ ......+n.
The statement must go as when the natural number n is entered as 1 the sum must be 1, here it will return the value 1 and when the natural number n is entered as 3 or any other other number greater than 1 so it will first calculate the sum of ( 3 +sum(2)) here it again calls the function and sum(n) replacing n now by 2.
So the function may be defined as
int sum(n)
{
if (n=1)
return 1;
else
return (n + sum(n-1));
}
So we see that "??" is replaced by n=1 so that when 1 is entered it returns the value 1 and does not to further else if greater than 1 is entered it will execute the next statements of the function.
Therefore "??" is n=1.
#SPJ2