Skip to content
This repository was archived by the owner on May 28, 2026. It is now read-only.

Latest commit

 

History

History
38 lines (34 loc) · 1.04 KB

File metadata and controls

38 lines (34 loc) · 1.04 KB

Recursion in C/C++

Recursion occurs when a function calls itself. For example, consider two implementations of the factorial function:

Iterative

?inline

int f(int n) {
  int res = 1, i = 1;
  while (i++ < n)
    res *= i;
  return res;
}

As seen here, mutable local variables can help you avoid recursion.

Recursive

?inline

int f(int n) {
  if (n == 0)
    return 1;
  else
    return n * f(n-1);
}

if (n == 0) here is known as a base case, at least one of which is necessary to prevent infinite recursion.

See Also

<:stackoverflow:874353689031233606> Is recursion ever faster than looping?
learncpp.com - Recursion
Wikipedia - Tail Call (important for optimizations)

?creditFooter 614056212803092480