C Program to Find Factorial using Recursion
This program calculates the factorial of a number using recursion in C. It demonstrates how a recursive function can call itself until a base condition is reached.
Concept Overview
A factorial of a number n (written as n!) is the product of all positive integers less than or equal to n. Using recursion, the factorial of n is defined as: n * factorial(n - 1), with factorial(0) = 1.
Program
C
#include <stdio.h>
// Recursive function to calculate factorial
unsigned long long factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 0)
printf("Factorial is not defined for negative numbers.\n");
else
printf("Factorial of %d is %llu\n", num, factorial(num));
return 0;
}
Output
Factorial of 12 is 479001600
Explanation
- The function `factorial()` takes an unsigned integer as input.
- If the input `i` is less than or equal to 1, the function returns 1 — this is the base case.
- Otherwise, it returns `i * factorial(i - 1)`, calling itself recursively.
- In `main()`, the factorial of 12 is calculated and printed.
Note: For large numbers, use `unsigned long long int` to prevent overflow. Iterative methods may be faster for very large inputs.
Codecrown