Home > Backend Development > C#.Net Tutorial > How to implement recursive algorithm in C language

How to implement recursive algorithm in C language

藏色散人
Release: 2019-02-28 14:00:04
Original
5812 people have browsed it

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();
}
Copy after login

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;
}
Copy after login

Output:

Factorial of 12 is 479001600
Copy after login

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;}
Copy after login

Output:

0	
1	
1	
2	
3	
5	
8	
13	
21	
34
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template