Recursion
Recursion refers to the method of using the function itself within its definition.
For example:
The syntax format is as follows:
void recursion()
{
statements;
... ... ...
recursion(); /* Function calls itself */
... ... ...
}
int main()
{
recursion();
}
Flowchart:
C language supports recursion, meaning a function can call itself. However, when using recursion, the programmer needs to define an exit condition from the function, otherwise it will enter an infinite loop.
Recursive functions play a crucial role in solving many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc.
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("%d 的阶乘为 %f\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result:
15 的阶乘为 1307674368000.000000
Fibonacci Series
The following example uses a recursive function to generate the Fibonacci series 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 result:
0
1
1
2
3
5
8
13
21
34