recursive call to function

A function that calls itself within its body is called a recursive call, and such a function is called a recursive function. Executing a recursive function will call itself repeatedly, entering a new layer with each call.

[Example] Use recursion to calculate n!. The formula for calculating factorial n! is as follows:

Program according to the formula:

  1. long factorial(int n){
  2. long result;
  3. if(n==0 || n==1){
  4. result = 1;
  5. }else{
  6. result = factorial (n -1 ) * n ; // recursive call
  7. }
  8. return result;
  9. }

This is a typical recursive function. After calling factorial, it will enter the function body, and the function will execute only when n==0 or n==1, otherwise it will always call itself.

Since the actual parameter of each call is n-1, that is, the value of n-1 is assigned to the formal parameter n, so the value of each recursive actual parameter is decremented by 1, until the final value of n-1 is 1. Call, the value of the formal parameter n is also 1, the recursion is terminated, and it will exit layer by layer.

For example, to find 5!, call factorial(5). After entering the factorial function body, since n=5, it is not equal to 0 or 1, so the execution result = factorial(n-1) * n;, that is result = factorial(5-1) * 5;, the next call factorial(4). This is the first recursion.

After four recursive calls, the value of the actual parameter is 1, which is the call to factorial(1). At this point, the recursion is over, and it starts to return layer by layer. The value of factorial(1) is 1, the value of factorial(2) is 1*2=2, the value of factorial(3) is 2*3=6, the value of factorial(4) is 6*4=24, and finally return The value factorial(5) is 24*5=120.

Note: In order to prevent recursive calls from going on indefinitely, there must be a means of terminating the recursive call within the function. The common method is to add conditional judgment. After a certain condition is met, no recursive call is made, and then return layer by layer.

Recursive calls are not only difficult to understand, but also expensive, and recursion is not recommended unless necessary. Many recursive calls can be replaced with iterations (loops).

[Example] Use the iterative method to find n!.

  1. long factorial(int n){
  2. int i;
  3. long result=1;
  4. if(n==0 || n==1){
  5. return 1;
  6. }
  7. for(i=1; i<=n; i++){
  8. result *= i;
  9. }
  10. return result;
  11. }

For the principle of function calling, please read the sections of " The Concept of Stack and Stack Overflow ", " What is a Function on the Stack " and " Detailed Analysis of an Example of Pushing and Popping a Function from the Stack" in " C Language and Memory " , then you will understand why recursive calls are expensive.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325477862&siteId=291194637