I would like to see the progression of the algorithm as it changes values in stack memory (in order to get a better understanding of its internal process in memory). Below is a correct source code that computes the recursive fibonacci.
The question is: how does the algorithm changes values internally in stack memory? Right below i made an attempt to show you the visual model i adopted to understand it.Sadly, i find it difficult to implement my visual model for the fibonacci but it is easy for the factorial !!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <cstdio>
#include <cstdlib>
int fib(int n)
{
int f;
if(n == 1)
f = 0;
else if(n == 2)
f = 1;
else
f =fib(n - 1) + fib(n - 2);
return f;
int main(void)
{
int i ;
for(i=1;i<11;i++)
printf("%d\t%d\n",i,fib(i) );
return EXIT_SUCCESS;
}
| |
To help you understand what i mean here is an example for the factorial.
My stack's memory visual model for the recursive factorial is :
fact(3)--->3*fact(2)--->2*fact(1)--->1 (winding round, aka push)
answer= 6<--- 3* 2 <----2* 1 <---1 (unwinding round, aka pop)
(i do not write the source code for the recursive factorial,google it,it is everywhere)
BUT for the fibonacci sequence how is it gonna look like?? i think the example below is not so correct:
.....................................--f(4)--..........--f(3)--
f(5)-->f(4) + f(3)--->(f(3)+f(2)) + (f(2)+ f(1))--->( (f(2)+f(1)) + 1 ) + (1 +0)
...missing text...confused!