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