I am trying to write a recursive function, but get an error in the line : n + sum(n-1); My compiler is German, so a poor translation of the error message would be: "void value not ignored as supposed to". Thanks for help!
void sum (int n)
{
if(n==0)
{
cout << n << endl;
}
else if(n>0)
{
n + sum(n-1);
cout << n << endl;
}
}
int main()
{
sum(3);
return 0;
}
In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). When there are too many function calls, or a function is missing a base case, JavaScript will throw this error.
Steps of analysis using recursion tree methodCalculate total number of levels in the recursion tree. Calculate cost of additional operations at each level by adding cost of each node present at the same level. Finally, add cost of each level to determine the total cost of recursion.
The “maximum recursion depth exceeded in comparison” error is raised when you try to execute a function that exceeds Python's built in recursion limit. You can fix this error by rewriting your program to use an iterative approach or by increasing the recursion limit in Python.
Every time the recursive function is called, it takes up stack space (we'll discuss this more exhaustively in the section) and space for its local variables are set aside. So actually, the recursive version takes up much more space overall than does the iterative version.
Notice that you've defined the function as
void sum (int n);
This function has no return value. However, in this code:
n + sum(n-1);
You are trying to add n
to the return value of sum(n - 1)
, which isn't legal because sum(n - 1)
doesn't produce a value.
To fix this, you probably will want to change the function so that it returns an int
. If you do this, you'll need to make other changes, such as adding return statements into the function, but it should help get you on the right track.
Hope this helps!
your sum method returns void, change it to int
int sum (int n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With