Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding an error in a recursive function?

Tags:

c++

recursion

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;
}
like image 932
Julius Avatar asked Nov 28 '13 21:11

Julius


People also ask

What is recursion error?

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.

How do you analyze a recursive function?

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.

How do you fix a recursive error?

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.

What is the main problem of a recursive function?

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.


2 Answers

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!

like image 173
templatetypedef Avatar answered Oct 17 '22 01:10

templatetypedef


your sum method returns void, change it to int

int sum (int n)
like image 36
LZR Avatar answered Oct 17 '22 02:10

LZR