Home >Backend Development >C#.Net Tutorial >How to implement recursive algorithm in C language
Recursion is a method calling itself. In programming languages, if a program allows you to call a function within the same function, it is called a recursive call of a function.
void recursion() { recursion(); /* 函数调用本身 */ } int main() { recursion(); }
C language supports recursion, that is, a function that calls itself. But when using recursion, the programmer needs to be careful in defining the exit condition of the function, otherwise it will enter an infinite loop.
Recursive functions are very useful for solving many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc.
Factorial of a number
The following example uses recursion to calculate the factorial function of a given number
#include <stdio.h> unsigned long long int factorial(unsigned int i) { if(i <= 1) { return 1; } return i * factorial(i - 1); } int main() { int i = 12; printf("Factorial of %d is %d\n", i, factorial(i)); return 0; }
Output:
Factorial of 12 is 479001600
Fibonacci Series
The following example uses a recursive function to generate a Fibonacci series for a given number
#include <stdio.h>int fibonacci(int i) { if(i == 0) { return 0; } if(i == 1) { return 1; } return fibonacci(i-1) + fibonacci(i-2);}int main() { int i; for (i = 0; i < 10; i++) { printf("%d\t\n", fibonacci(i)); } return 0;}
Output:
0 1 1 2 3 5 8 13 21 34
Recommended related C language video tutorials: "C Tutorial"
This article is an introduction to the C language recursive algorithm. I hope it will be helpful to friends who need it. help!
The above is the detailed content of How to implement recursive algorithm in C language. For more information, please follow other related articles on the PHP Chinese website!