C Program to Find Factorial Using Tail Recursion
Tail recursion is a special type of recursion where the recursive call is the last action performed by the function, allowing compilers to optimize memory usage.
1. Problem Statement
Write a C program to calculate the factorial of a number using a tail-recursive function.
2. Algorithm
Step 1: Start.
Step 2: Read an integer input from the user.
Step 3: Call a recursive function passing the number and an accumulator (initialized to 1).
Step 4: Base case: if n <= 1, return the accumulator.
Step 5: Recursive case: return the function call with (n-1) and (accumulator * n).
Step 6: Print the result and exit.
3. C Program Using Tail Recursion
C
Factorial using tail recursion
#include <stdio.h>
long long tail_factorial(int n, long long accumulator) {
if (n <= 1)
return accumulator;
return tail_factorial(n - 1, n * accumulator);
}
int main() {
int num = 5;
printf("Factorial of %d is %lld", num, tail_factorial(num, 1));
return 0;
}
4. Output
Factorial of 5 is 120
Notes
Tail recursion is memory efficient because the function does not need to perform additional operations after the recursive call, allowing the current stack frame to be reused.