C Recursion

Recursion refers to the method of using the function itself within the definition of a function.

For example:
Once upon a time, there was a mountain, and in the mountain there was a temple, and in the temple there was an old monk telling a story to a young monk! What was the story? "Once upon a time, there was a mountain, and in the mountain there was a temple, and in the temple there was an old monk telling a story to a young monk! What was the story? 'Once upon a time, there was a mountain, and in the mountain there was a temple, and in the temple there was an old monk telling a story to a young monk! What was the story? ...'"

The syntax format is as follows:

void recursion() { statements; ... ... ... recursion(); /*A function calls itself*/ ... ... ... } int main() { recursion(); }

Flowchart:

The C language supports recursion, meaning a function can call itself. However, when using recursion, programmers need to be careful to define a condition for exiting the function; otherwise, it will fall into an infinite loop.

Recursive functions play a crucial 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:

Example

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

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

15 的阶乘为 1307674368000.000000

Fibonacci sequence

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

Example

#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
other extensions