Sobes.tech
Junior

What is recursive behavior?

sobes.tech AI

Answer from AI

Execution of code or functions that call themselves.

Main elements:

  • Base case: The condition under which recursion stops. Without it, infinite recursion occurs.
  • Recursive case: Part of the function where it calls itself, usually with a modified argument.

Example (calculating factorial):

func factorial(_ n: Int) -> Int {
    // Base case
    if n <= 1 {
        return 1
    }
    // Recursive case
    return n * factorial(n - 1)
}
// Example call
let result = factorial(5) // 120

Advantages:

  • Elegant solution for problems with a self-similar structure (e.g., tree traversal).
  • More readable code in some cases.

Disadvantages:

  • Can consume a lot of memory (call stack).
  • Stack overflow possible with too deep recursion.
  • Sometimes less efficient than iterative solutions.