For example: I want to ask 1+2+3+4+. A value of +100.
Iterative approach: from 1 to 100, along the downward accumulation. 1+2=3,3+3=6,6+4=10,10+5=15 ...
program indicates that
int i=1,sum=0;
while (i<=100) {
}
Recursive approach: I asked for the cumulative value of 1 to 100, if I have obtained a cumulative value of 1 to 99, add this value 100 is 1 to 100 of the cumulative value, to get the cumulative value of 1 to 99, if you have been the cumulative value of 1 to 98, add this value 99, is 1 to 99 of the cumulative value ... Finally I want to get 1 to 2 of the cumulative value, if I get 1 of its own cumulative value, plus 2, 1 of its own cumulative value is obviously 1. So now we have a cumulative value of 1 to 2, adding 3 to the sum of 1 to 3. Last until you get a cumulative value of 1 to 100.
The program indicates that the function calls itself, which is the typical feature of the recursive method
int getsum (int n)
{
if (n<=0) return 0;
else return n+getsum (n-1);
}
In the above example, in fact, the final result of recursion is also done by iterative method, but in the process of the program can not be visualized. Both can do a good job of computing, the difference is in the way of thinking, which leads to different computational methods: iterative is positive thinking, from start to finish thinking, recursion is reverse thinking, he assumes that we have obtained partial results (assuming I already know the cumulative value of 1 to 99, Adding this value to 100 gives us a cumulative value of 1 to 100, which goes back from the tail to the head, thus simplifying the problem (which, of course, cannot be seen, is simply understandable)
The difference between recursive algorithm and iterative algorithm