The difference between recursive algorithm and iterative algorithm

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.