Thursday, October 20, 2011

Function Recurrence and Fibonacci Element

Let's say we want to calculate n-element value of Fibonacci sequence and we do not want to write to much code. The best solution is to use function recurrence. Here is the sample code:


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

Wouldn't it be nice to see how computer will proceed through stack to return the correct number?
I did it for you. We are starting at green box calculating value of 5th element. Have fun!

Function flow

No comments:

Post a Comment