1, if the recursion is the tail recursion, the use of the loop can be eliminated, tail recursion is the function at the end of the recursive call this function, the following format is satisfied:
int function (int n) {if (n==0) return 1;else return function (n-1);}
The tail recursion uses the loop, uses the result of the N=1, defines a variable to remember the res, then loops slowly calculates the n=2, 3 .... The result is that each time the value of n is calculated, the res will remember that each time the value of the function is computed using res, the following gives an example of calculation
#include <stdio.h>
Recursive method int fib (int n) {if (n==1) return 1;if (n==0) return 0;else return fib (n-1) +fib (n-2);}
Non-recursive method int fib2 (int n) {if (n==1) return 1;else if (n==0) return 0;int fib0=0;int fib1=1;int result=0;for (int x=2;x<=10;x+ +) {Result=fib0+fib1;fib0=fib1;fib1=result;} return result;} void Main () {int A=fib (ten), int b=fib2 (TEN);p rintf ("A's value is:%d\n", a);p rintf ("B's value is:%d\n", b);}
2, if the non-recursive need to be based on the stack to eliminate recursion, the detailed process is visible: Shang, data structure 129 pages.
Ways to eliminate recursion