C recursion


Recursion refers to the method of using the function itself in the definition of the function.

For example:
Once upon a time there was a mountain, and there was a temple in the mountain. There was an old monk in the temple, and he was telling stories to the young monk! What's the story? "Once upon a time there was a mountain, and there was a temple in the mountain. There was an old monk in the temple, and he was telling a story to the young monk! What is the story? 'Once upon a time, there was a mountain. There was a temple in the mountain. There was an old monk in the temple. He was telling a story to the young monk. Tell a story to the little monk! What is the story? ...'"

The syntax format is as follows:

void recursion(){
   recursion(); /* 函数调用自身 */}int main(){
   recursion();}

C language supports recursion, that is, a function can call itself. But when using recursion, programmers need to pay attention to defining a condition for exiting from the function, otherwise it will enter an infinite loop.

Recursive functions play a vital role in solving many mathematical problems, such as calculating the factorial of a number, generating the Fibonacci sequence, and so on.

Factorial of a Number

The following example uses a recursive function to calculate the factorial of a given number:

#include <stdio.h>double factorial(unsigned int i){   if(i <= 1)   {      return 1;   }   return i * factorial(i - 1);}int  main(){    int i = 15;
    printf("%d 的阶乘为 %f\n", i, factorial(i));    return 0;}

When the above code is compiled and executed, It will produce the following results:

15 的阶乘为 1307674368000.000000

Fibonacci Sequence

The following example uses a recursive function to generate the Fibonacci Sequence for a given number:

#include <stdio.h>int fibonaci(int i){   if(i == 0)   {      return 0;   }   if(i == 1)   {      return 1;   }   return fibonaci(i-1) + fibonaci(i-2);}int  main(){    int i;    for (i = 0; i < 10; i++)    {
       printf("%d\t%n", fibonaci(i));    }    return 0;}

When the above code is compiled and executed, it produces the following results:

0112358132134