Home  >  Article  >  Backend Development  >  What are the exit conditions for a recursive function in C++?

What are the exit conditions for a recursive function in C++?

PHPz
PHPzOriginal
2024-04-17 11:33:01362browse

C The exit conditions of recursive functions include: Baseline conditions: Check whether the function reaches a state that can directly return results, usually judging whether a certain condition or parameter value meets the threshold. Recursion termination condition: Alternative to or in addition to the baseline condition, ensuring that the function stops after a certain number of recursive calls, by tracking the recursion depth or setting a maximum recursion depth limit.

C++ 递归函数的退出条件是什么?

C Exit conditions for recursive functions

Recursive functions solve problems by calling themselves repeatedly. To prevent getting stuck in an infinite recursive loop, clear exit conditions must be defined. In C, exit conditions are usually implemented in the following ways:

1. Baseline condition:

  • is used to determine when a function reaches a point where it can directly return a result. state.
  • Usually check whether a certain condition is met or the parameter value reaches a certain threshold.
  • When the baseline condition is true, the function will return directly.
bool isEven(int n) {
  if (n == 0) {  // 基线条件:当 n 为 0 时,返回 true
    return true;
  } 
  else {
    return isEven(n - 1);  // 递归调用
  }
}

2. Recursive termination condition:

  • As an alternative or supplement to the baseline condition.
  • is used to ensure that the function stops after a certain number of recursive calls.
  • Achieved by tracking the recursion depth or setting a maximum recursion depth limit.
int fibonacci(int n) {
  if (n <= 1) {  // 基线条件:当 n <= 1 时,返回 n
    return n;
  } 
  else if (n > MAX_RECURSION_DEPTH) {  // 递归终止条件:当递归深度超过限制时,返回错误值
    return -1;
  } 
  else {
    return fibonacci(n - 1) + fibonacci(n - 2);  // 递归调用
  }
}

Practical case

The following example function calculates the factorial of a given number:

int factorial(int n) {
  if (n == 0) {  // 基线条件:当 n 为 0 时,返回 1
    return 1;
  } 
  else {
    return n * factorial(n - 1);  // 递归调用
  }
}

The above is the detailed content of What are the exit conditions for a recursive function in C++?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn