Murtaza Fazal's Blog

Murtaza Fazal's Blog
Murtaza Fazal's Blog

Saturday, December 5, 2009

Tracing Recursive calls in Fibonacci Series


In mathematics, the Fibonacci numbers are the numbers in the following sequence:

0 , 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...


By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.

int F(int num)
{
      if ( num <=1)
           z = num;
     else
           z =  F(n-1) + F(n-2);
     return z;
}

In this function , if we pass n, it should return n+1th term , e.g passing 6 will return 8 so let suppose we pass 5 to the function F then in this case, it will call the function for 5. It will test either if num (which is 5 at the moment) is with <= 1? NO, hence it will move to the else part where it will call the function F again for 2 new values and their final sum will be restored in z. so the equation will become like this

z = F(4) + F(3);

Now we’ll use the first come first bases rule and go and evaluate F(4) then F(3) . Hence F(4) will be called exactly as F(5) was called, it will again test for <=1 which is NO again and then it will call again the 2 recursive functions for F(4) i.e

z = F(3) + F(2);

This can be better explained in terms of a TREE






The bold objects are the values returned by the if clause of the function F. Blue color numbers are the one being returned to the previous state from the stack.