Tail Recursion and Iteration are Equivalent: Any algorithm that can be implemented with iteration (loops) can also be implemented with tail recursion, and vice versa. Smart compilers optimize tail recursive code to execute similarly to iterative code.
Iterative Factorial Function:
int factorial(int n) {
int ans = 1;
while (n > 0) {
ans = ans * n;
n--;
}
return ans;
}
int ans = 1;
while (n > 0)
ans
by n
.n
.Tail-Recursive Factorial Function:
int factorial_helper(int n, int acc) {
if (n <= 0) {
return acc;
}
return factorial_helper(n - 1, n * acc); // Tail call
}
int factorial(int n) {
return factorial_helper(n, 1); // Initial call with accumulator
}
factorial_helper
with parameters n
and acc
.