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.
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);
}
imagine if you have a big picture..., but in this case a non-recursive implementation is very hard to implement.
About fibonacci:
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;
}
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.
So please consider in the future whether to use recursion or loops, now that you now what these are.