C and pointers Chapter 7 function recursion and iteration

Source: Internet
Author: User

The C language supports the implementation of recursive functions through the runtime stack. recursive functions call their own functions directly or indirectly. It is often used as a recursive implementation by Fibonacci, and the efficiency is not high.

N <1; FIB (1) = 1

N = 2; FIB (2) = 1

N> 2; FIB (n) = fib (n-1) + fib (n-2 );

Each recursive call will trigger two other recursive calls, which will continue to be triggered, resulting in a large amount of redundant computing. For example, in the calculation of Fib (10), FIB (3) is calculated 21 times;

 
# Include <stdio. h> int fib (n) {static COUNT = 0; If (n <= 2) return 1; if (n = 3) {count ++; printf ("Call fib (3) % d times \ n", count);} return fib (n-1) + fib (n-2);} int main () {printf ("% d", FIB (10); While (1); Return 0 ;}

Call 21 times:

Except for one call, all other computation is redundant. Because the function is tail recursion, it can be easily converted to an iteration loop for implementation.

The following is implemented through iteration.

Long fib (int n) {long result; long previus_result; long previus_older_result; Result = previous_result = 1; while (n> 2) {n-= 1; previus_result = result; previous_older_result = previous_result; Result = previous_result + previous_older_result;} return result ;}

The advantage of recursion is readability, But improper use will also increase the overhead.

The following example uses recursion to convert integers into character forms, such as 4321 to '4', '3', '2', and '1 '.

 
Void num_to_char (INT num) {int quotient; quotient = num/10; If (quotient! = 0) {num_to_char (quotient);} printf ("% C", num % 10 + '0 ');}

Every time a recursive function is executed, it must be closer and closer to the exit. The exit here is when quotient is 0.

 

C and pointers Chapter 7 function recursion and iteration

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.