🔄📚Intermediate
Factorial Using Recursion
Recursive factorial calculation
Recursion is when a function calls itself. Factorial is a classic example:
n! = n × (n-1)! with base case: 0! = 1
Program Code
factorial_recursion.c
C
1#include <stdio.h>23// Recursive function4long long factorial(int n) {5 // Base case6 if (n == 0 || n == 1) {7 return 1;8 }9 // Recursive case10 return n * factorial(n - 1);11}1213int main() {14 int num;15 16 printf("Enter a number: ");17 scanf("%d", &num);18 19 if (num < 0) {20 printf("Factorial not defined for negative numbers\n");21 } else {22 printf("%d! = %lld\n", num, factorial(num));23 }24 25 return 0;26}Output
Enter a number: 6
6! = 720
Step-by-Step Execution:
1
factorial(6)
Returns 6 × factorial(5)
2
factorial(5)
Returns 5 × factorial(4)
3
factorial(4)
Returns 4 × factorial(3)
4
factorial(3)
Returns 3 × factorial(2)
5
factorial(2)
Returns 2 × factorial(1)
6
factorial(1)
Base case: returns 1
7
Unwind
2×1=2, 3×2=6, 4×6=24, 5×24=120, 6×120=720
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials