You might find this interesting to read Micko.
http://mitpress.mit.edu/sicp/full-te...ml#%_sec_1.2.1
Printable View
You might find this interesting to read Micko.
http://mitpress.mit.edu/sicp/full-te...ml#%_sec_1.2.1
The fibonacci series is a bad example of recursion because the number can be calculated with a single way loop. On the other hand if you want to make operations on a graph, like doing a depth search, recurssion is imperative, unless you want a PhD in non-recursive functions.
I'm saying this because calling a function requires pushing arguments and the return point adress to the stack, which could in some cases spend to much memory, or even overflow the stack, causing the program to crash.
This could happen with the floodfill algorithm to fill regions of pixels.
imagine if you have a big picture..., but in this case a non-recursive implementation is very hard to implement.Code:void floodfill(int x, int y){
if(/*point is on contour, or has countour color*/)
return;
floodfill(x+1, y);
floodfill(x-1, y);
floodfill(x, y+1);
floodfill(x, y-1);
}
About fibonacci:
The second implementation is non-recursive, therefore much lighter to the computer, and in this case very optimized, because the function runs a single loop, instead of calling itself twice.Code:int fibrec(int n){
if(n<2) return 1;
return fibrec(n-1)+fibrec(n-2);
}
int fibnrec(int n){
int n0=0, n1=1, i=0;
while(i++<n){/*sum cicle*/
if(n0>n1)
n1=n0+n1;
else
n0=n1+n0;
}
return n0>n1?n0:n1;
}
So please consider in the future whether to use recursion or loops, now that you now what these are. :D
Actually going from recursive to non recursive is a completly machnical process. The C++ class I will be taking in the fall actually goes into it. Only thing that makes it difficult is the number of recursion points.
Exactly! ;)Quote:
Originally Posted by Thantos