Home>Article>Backend Development> How to implement recursive algorithm in C language

How to implement recursive algorithm in C language

藏色散人
藏色散人 Original
2019-02-28 14:00:04 5623browse

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.

How to implement recursive algorithm in C language

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  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 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn