function recursion and iteration

Source: Internet
Author: User

Recursive defect: When the stack process is executed more often, the computational amount is too large. But each tail recursion can be written as a loop (using a non-native word is iterative)

The FABONACII sequence is implemented in an iterative way:

#include <stdio.h>int fibonacii (int n) {    int temp = 0;    int a = 1;//Remember to assign the first two numbers the initial value    int b = 1;    if (n <= 2)        return 1;    while (n > 2)    {        temp = a + b;        A = b;        b = temp;//avoid written a = temp; b = A; At this point a has changed!=1 and then the assignment to B has no meaning        n--;//adjust the value stored in AB to move forward    }    return temp; int main () {    printf ("%d\n", Fibonacii (6));    return 0;}


To implement factorial in an iterative way:

#include <stdio.h>int fac (int n) {    int ret = 1;    while (n)    {        ret = ret * N;        n--;//ret = 1*n,ret = N (n-1) .... Return back to    ret;} int main () {    printf ("%d\n", FAC (3));    return 0;}


function recursion and iteration

Related Article

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.