Search code examples
algorithmrecursion

Finding sum of fibonacci numbers recursively


I'm a bit stuck here. I know a particular fibonacci number can be found recursively as so:

int fib (int n)
{
    if (n <= 1)
        return n;

    else 
        return fib(n-1) + fib(n-2);
}

And I know iteratively I could call that function n times to find the sum of fibonacci numbers

int sum = 0;
for (int i = 0; i < n; i++)
{
    sum += fib(i);
}

But I'm having a hard time coming up with a recursive function to find the sum. I don't think it would be much different than the original fibonacci function. (This is for an assignment aimed at improving my ability to write ocaml syntax, not writing recursive functions)


Solution

  • Since no one else is bothering to answer your question, here you go:

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