Recursion is an algorithmic technique where a function calls itself to solve smaller instances of the same problem. Every properly constructed recursive function must have two components: a Base Case (which terminates the recursion) and a Recursive Step.
#include <iostream>
// Standard non-tail recursion (Builds up call stack O(N))
unsigned long long factNormal(int n) {
if (n <= 1) return 1;
return n * factNormal(n - 1); // Multiplication happens AFTER return!
}
// Tail-recursive version (Accumulator passes state forward)
unsigned long long factTail(int n, unsigned long long accumulator = 1) {
if (n <= 1) return accumulator;
return factTail(n - 1, n * accumulator); // Tail call! Compiler optimizes to loop!
}
int main() {
std::cout << "10! = " << factTail(10) << std::endl; // 3628800
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Function execution and stack frames.
Converting recursive algorithms into iterative loops.
Recursive binary search and Fibonacci.