Julius
Julius

Reputation: 69

Understanding an error in a recursive function?

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;
}

Upvotes: 5

Views: 213

Answers (7)

slecorne
slecorne

Reputation: 1718

Your sum() method should return a value, it should return the sum. You should define it like this

int sum (int n)
{
if(n==0)
{
 cout << n << endl;
 return 0;
}
else if(n>0)
{
    cout << n << endl;
    return n + sum(n-1);
 }
 }

Upvotes: 2

Sylwester
Sylwester

Reputation: 48745

  • A recursive function needs to return something in each tail position.
  • A recursive function needs to have made the problem smaller at each recursion.

Here is one example of how to do it:

int sum (int n)
{
    return n == 1 ? 1 : n + sum_rec(n-1);
}

int main()
{
   cout << sum(3) << endl;
   return 0;
}

A better one if you C compiler does tail call optimization:

// just a helper for sum_it
int sum_aux (int n, int accumulator)
{
    return n == 0 ? accumulator : sum_rec(n-1, accumulator + n);
}

int sum_it (int n)
{
    sum_aux(n, 0);
}

Upvotes: 0

Julius
Julius

Reputation: 69

I got it. Was kinda stupid from me. It has to be of course n = n + sum(n-1); And an int function. Thanks guys.

Upvotes: 0

templatetypedef
templatetypedef

Reputation: 372704

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!

Upvotes: 5

David Grayson
David Grayson

Reputation: 87386

When you wrote "void sum" you told the compiler that sum would not return anything. This is wrong. Try replacing "void" with int.

Upvotes: 1

jdc
jdc

Reputation: 339

You try to add n and sum(n-1), but sum has no return value, so this is an error. You should modify sum to return an int, and add the return statements in the two if bodies.

Upvotes: 1

LZR
LZR

Reputation: 958

your sum method returns void, change it to int

int sum (int n)

Upvotes: 3

Related Questions