Compute the factorial of a number in C using iterative loops and recursive functions. Full code, step trace, and overflow handling explained.
Understanding Factorial in Mathematics
The factorial of a non-negative integer n, denoted as $n!$, is the product of all positive integers less than or equal to n:
text (ISO Standard)n! = n × (n - 1) × (n - 2) × ... × 1
Special base case: $0! = 1$. Note that factorials grow extremely fast, so in C programming we typically use unsigned long long to prevent integer overflow for values up to $n = 20$.
Method 1: Iterative Approach (Loop)
The iterative approach uses a standard for loop, multiplying an accumulator variable from $1$ up to n.
c (ISO Standard)#include <stdio.h> unsigned long long factorialIterative(int n) { if (n < 0) { return 0; /* Factorial is undefined for negative integers */ } unsigned long long fact = 1; for (int i = 1; i <= n; i++) { fact *= (unsigned long long)i; } return fact; } int main() { int number = 10; printf("Calculating factorial of %d (Iterative):\n", number); unsigned long long result = factorialIterative(number); printf("%d! = %llu\n", number, result); return 0; }
Method 2: Recursive Approach
Recursion breaks the problem into subproblems: $n! = n × (n-1)!$ with the terminating base case $0! = 1$.
c (ISO Standard)#include <stdio.h> unsigned long long factorialRecursive(int n) { /* Base cases */ if (n < 0) { return 0; } if (n == 0 || n == 1) { return 1; } /* Recursive step */ return (unsigned long long)n * factorialRecursive(n - 1); } int main() { int number = 7; printf("Calculating factorial of %d (Recursive):\n", number); unsigned long long result = factorialRecursive(number); printf("%d! = %llu\n", number, result); return 0; }
Sample Output
text (ISO Standard)Calculating factorial of 10 (Iterative): 10! = 3628800
Complexity Analysis
| Approach | Time Complexity | Auxiliary Space | Stack Overhead |
|---|---|---|---|
| Iterative | O(n) | O(1) | None |
| Recursive | O(n) | O(n) | n Call Frames |
Related Guides & Algorithms
- Practice recursion with our Fibonacci Series in C program.
- Master functions and recursion stacks in Functions in C Programming.
- Test edge cases interactively in the Online C Compiler.