0

So I'm just starting to learn about recursion and I'm confused as to how avoid this problem. I will write a function that needs to store a variable, like a sum, but I have to declare the variable in the function so every time the recursive call is made the variable gets initialized again. How can I fix this? I think a helper function of some short but I'm not really sure.

int fib_tail(int n)
{    
    int fibResult = 0;
    int x = 0; // used for bottom-up approach
    if (n == 0) {
        return 0;
    }
    if (n == 1) {
        return 1;
    }
    if (n > 1 && x <= n) {
        fibResult += fib(x);
    }
    ++x;
    return fib_tail(n);
}
2
  • The variable accumulating the result is typically passed in as a parameter. Commented Oct 4, 2015 at 3:59
  • My bad for not providing an example. Here's an example of an attempt at making a tail recursive number for Fibonacci. Commented Oct 4, 2015 at 13:34

1 Answer 1

4

It would help if you provided your code. However usually you pass whatever you need in and return the result.

An example:

int Sum(Node* node)
{
    if (node == 0)
        return 0;
    return node->value + Sum(node->next);
}

Edit

Here is what I would do in your example:

int fib_tail(int n)
{    
    if (n <= 0) {
        return 0;
    }
    if (n == 1) {
        return 1;
    }
    return fib_tail(n-1) + fib_tail(n-2);
}

Ide one: http://ideone.com/hS2s38

Sign up to request clarification or add additional context in comments.

2 Comments

Why do you have a current-variable... this is not needed in any way... you even missed it yourself in your code while calling Sum :D
Haha, so easy to make simple errors when making an example. Thanks @SkryptX

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.