Recursive definition
A function calls itself directly or indirectly
Let’s take a look at a well-written paragraph
"When a function is called while another function is running, the system needs to complete three things before running the called function:
(1) Pass all actual parameters, return address and other information to the called function to save
(2) Allocate storage area for local variables of the called function
(3) Transfer control to the calling function according to the return address saved by the called function
When there are multiple functions that constitute nested calls, according to the principle of call-after-first-return, the information transfer and control transfer between the above-mentioned functions must be realized through the stack, that is, the system arranges the data space required by the entire program when it is running. In a stack, whenever a function is called, a storage area is allocated on the top of the stack. When a function exits, its storage area is released. The data area of the currently running function must be at the top of the stack. " ——"Data Structure and Algorithm", Yan Weimin
The above sentence is suitable for function A to call function B, and function A to call function A [ie recursion ] is the same reason
There are many recursive classifications, which can be understood through examples
A few examples of recursion
Example 1: Use recursion to find the sum of 1+2+3+......+100
#include <stdio.h>
/*递归法求1+2+3+...+100啊*/
int f(int n)
{
if (n == 1)
return 1;
else
return f(n-1) + n;
}
int main(void)
{
printf("%d", f(100));
return 0;
}
Example 2: Find the factorial (can be written in a loop or recursively)
① Find the factorial by the round-robin method
#include <stdio.h>
/*循环法求阶乘*/
int f(int n)
{
int fac = 1;
int i;
if (n == 0)
return 0;
for (i = 1; i <= n; i++)
fac = fac * i;
return fac;
}
int main(void)
{
printf("%d", f(2));
return 0;
}
② Recursive method to find factorial
#include <stdio.h>
/*递归法求阶乘啊*/
int f(int n)
{
if (n == 1)
return 1;
else
return f(n-1)*n;
}
int main(void)
{
printf("%d", f(4));
return 0;
}
Example 3:
Tower of Hanoi
Example 4:
Walk the maze