a function calls itself in its function body calledRecursive invocation, this function is calledRecursive Functions. executing a recursive function calls itself repeatedly, entering a new layer each time it is called.
The example calculates the n! with recursion. Factorial n! The calculation formula is as follows:
Programming by formula:
- Long factorial (int n) {
- long result;
- if (n= =0 | | n= =1) {
- Result = 1;
- }else{
- Result = factorial(n-1) * n; //Recursive invocation
- }
- return result;
- }
This is a typical recursive function. After calling factorial, the function body is entered, and the function executes the end only when n==0 or n==1, otherwise it is called itself.
because each invocation of the argument is n-1, that is, the value of the n-1 is assigned to the parameter n, so that the value of each recursive argument is reduced by 1, until the value of the last n-1 is 1 o'clock to make a recursive call, the value of the parameter n is also 1, the recursion terminates, will exit by layer.
For example, ask for 5, which is called factorial (5). When entering the factorial function body, because n=5, not equal to 0 or 1, so the execution
result = factorial(n-1) * n;
, i.e.
result = factorial(5-1) * 5;
, which is then called
factorial(4)
. This is the first time recursion.
after making four recursive calls, the value of the argument is 1, which is called factorial (1). At this point the recursion is over, and it begins to return by layer. The value of factorial (1) is 1,factorial (2) with a value of 1*2=2,factorial (3) for 2*3=6,factorial (4) and the last return value is 6*4=24 (5) for factorial.
Note: In order to prevent recursive calls from being made without terminating, there must be a means of terminating recursive calls within the function. The common approach is to add conditional judgments, satisfy a certain condition, and then no longer make recursive calls, and then return by layer.
recursive invocation is not only difficult to understand, but also expensive, and it is not recommended to use recursion if it is not necessary. Many recursive calls can be replaced by iterations (loops).
The example uses the iterative method to find the n!.
- Long factorial (int n) {
- int i;
- long result=1;
- if (n= =0 | | n= =1) {
- return 1 ;
- }
- for (i=1; i<=n; i+ +) {
- Result *= i;
- }
- return result;
- }
-
Expand Reading
Recursively
-
finding Fibonacci numbers, allowing you to find recursive defects and efficiency bottlenecks
Recursive invocation of C-language functions