How to call a recursive function in the C language?

In C language, recursive functions can achieve recursion by calling themselves within the function. When calling a recursive function, it is important to keep the following points in mind:

  1. Defining the termination condition of recursion is crucial to prevent the recursion from running indefinitely. This condition must be met for the recursion to stop and return a result within the recursive function.
  2. Handle the current layer logic before making the recursive call: Before making the recursive call, it may be necessary to first handle the logic of the current layer, such as calculations, assignments, etc.
  3. Passing parameters: When making a recursive call, it is necessary to pass parameters to the next level of the recursive function. Typically, the values of the parameters will change as they approach the termination condition.

Here is an example of a recursive function that calculates factorial.

#include <stdio.h>

int factorial(int n) {
    // 终止条件
    if (n == 0) {
        return 1;
    }
  
    // 当前层逻辑处理
    int result = n * factorial(n - 1);
  
    return result;
}

int main() {
    int n = 5;
    int result = factorial(n);
  
    printf("Factorial of %d is %d\n", n, result);
  
    return 0;
}

In the above example, the recursive function “factorial” is used to calculate factorials. When n is equal to 0, the termination condition is met and 1 is returned. Otherwise, n is multiplied by factorial(n-1) to get the result. The “factorial” function is called in the main function, passing in the parameter 5 to calculate the factorial of 5 and print the result.

When the program is executed, the output is: The factorial of 5 is 120.

bannerAds