Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

C Recursive


May 11, 2021 C


Table of contents


C Recursive

Recursion repeats the processing of a project in a self-similar way. S imilarly, in a programming language, the function itself is called inside the function, called a recursive call. As follows:

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

int main()
{
   recursion();
}

The C language supports recursion, that is, a function can call itself. However, when using recursion, the programmer needs to be careful to define a condition to exit from the function, otherwise he or she will enter an infinite loop.

Recursive functions play an important role in solving many mathematical problems, such as calculating the order of a number, generating fibonachi columns, and so on.

The order of the number

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

#include <stdio.h>

int factorial(unsigned int i)
{
   if(i <= 1)    {
return 1;
} 
return i * factorial(i - 1); }

int  main() {
int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
} 

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

Factorial of 15 is 2004310016

Fiponachi number column

The following example uses a recursive function to generate a given number of Fiponachi columns:

#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:

0 1   1   2   3   5   8   13  21  34