If you’ve just started learning C programming, the factorial program is probably one of the first “real” logic-building exercises you’ll run into — right alongside the Fibonacci series in C and the prime number program in C. It looks simple on the surface, but it quietly teaches you loops, recursion, functions, overflow handling, and time complexity — all in one small program.
Quick answer: The factorial of a number n (written as n!) is the product of all positive integers from 1 to n. In C, you calculate it using a loop (for or while) or a recursive function that multiplies numbers until it reaches 1. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
In this guide, you’ll learn the factorial formula, multiple ways to write the factorial program in C (loops, recursion, functions), the algorithm behind it, how to handle large numbers and negative inputs, common mistakes beginners make, and the time and space complexity of each approach — with full code and output for every method.
What is Factorial?
The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n! and is a fundamental concept in mathematics, combinatorics, and computer science — used in permutations, combinations, probability, and algorithm analysis.
Factorials grow extremely fast. This rapid growth is exactly why the factorial program is such a popular teaching example in C — it shows you how loops behave, how recursion unwinds, and how quickly a data type like int can overflow.
Factorial Formula
The mathematical formula for factorial is:
n! = n × (n-1) × (n-2) × ... × 2 × 1
This can also be written recursively, which is exactly what makes it perfect for demonstrating recursion in C:
n! = n × (n-1)! for n > 0
0! = 1 (base case)
This recursive definition is the backbone of the recursive factorial program you’ll see later in this article.
Factorial Example
Let’s calculate a few factorials manually to see the pattern before jumping into code.
| n | Calculation | n! |
|---|---|---|
| 0 | (defined as base case) | 1 |
| 1 | 1 | 1 |
| 2 | 2 × 1 | 2 |
| 3 | 3 × 2 × 1 | 6 |
| 4 | 4 × 3 × 2 × 1 | 24 |
| 5 | 5 × 4 × 3 × 2 × 1 | 120 |
| 6 | 6 × 5 × 4 × 3 × 2 × 1 | 720 |
| 10 | 10 × 9 × … × 1 | 3,628,800 |
Notice how fast the values climb — by the time you reach 10!, you’re already past 3.6 million. This growth rate is important to keep in mind when you get to the section on large numbers later in this article.
Factorial Program in C
Now let’s write the actual C program. The simplest and most beginner-friendly version uses a for loop to multiply numbers from 1 up to n.
C Program to Find Factorial
#include <stdio.h>
int main() {
int n;
long long factorial = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n < 0) {
printf("Factorial of a negative number does not exist.\n");
} else {
for (int i = 1; i <= n; i++) {
factorial *= i;
}
printf("Factorial of %d = %lld\n", n, factorial);
}
return 0;
}
This program takes an integer input from the user, checks whether it’s negative, and if not, multiplies every number from 1 to n in a loop, storing the running product in the factorial variable.
Output
Enter a positive integer: 5
Factorial of 5 = 120
Try it again with a different input:
Enter a positive integer: 7
Factorial of 7 = 5040
How the Program Works
Here’s a step-by-step breakdown of what happens when you enter n = 5:
factorialis initialized to1(this is important — starting at0would make every result0).- The loop runs with
i = 1, 2, 3, 4, 5. - On each iteration,
factorial = factorial * i. - After the loop:
factorial = 1 × 1 × 2 × 3 × 4 × 5 = 120. - The result is printed using
printf.
The long long data type is used instead of int because factorial values grow quickly and can easily exceed the storage limit of a regular int — something we’ll cover in more detail in the large numbers section below.
Algorithm to Find Factorial in C
Before translating logic into code, it helps to write out the algorithm in plain steps. This is also useful if you’re preparing for viva questions or lab exams, similar to how you’d approach the algorithm for a prime number check in C.
Algorithm: Find Factorial of a Number
- Start
- Declare variables
n,i, andfactorial - Initialize
factorial = 1 - Read the value of
nfrom the user - If
nis negative, display an error message and stop - Otherwise, repeat steps 7–8 for
i = 1ton - Multiply
factorial = factorial × i - Increment
i - Print the value of
factorial - Stop
This algorithm maps directly onto both the for loop and while loop versions of the program — the only difference is how the repetition (step 6–8) is implemented.
Factorial Program in C Using for Loop
The for loop version is the most common way to write a factorial program in C because the loop counter, condition, and increment are all declared in a single line, making the code compact and easy to trace.
#include <stdio.h>
int main() {
int n;
long long fact = 1;
printf("Enter a number: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
printf("Factorial of %d is %lld\n", n, fact);
return 0;
}
Output:
Enter a number: 6
Factorial of 6 is 720
The for loop is a good fit here because you already know exactly how many times you need to repeat the multiplication — from 1 to n. This kind of fixed-count repetition is what for loops in C are designed for, and it’s a pattern you’ll reuse constantly when you move on to loop-heavy programs like the Fibonacci series in C.
Factorial Program in C Using while Loop
If you’d rather control the loop manually — useful when the number of iterations isn’t fixed in advance — a while loop works just as well.
#include <stdio.h>
int main() {
int n, i = 1;
long long fact = 1;
printf("Enter a number: ");
scanf("%d", &n);
while (i <= n) {
fact = fact * i;
i++;
}
printf("Factorial of %d is %lld\n", n, fact);
return 0;
}
Output:
Enter a number: 6
Factorial of 6 is 720
The logic is identical to the for loop version — only the syntax changes. Here, the counter i is initialized outside the loop, and you’re responsible for incrementing it manually inside the loop body. Forgetting the i++ line is a classic beginner mistake that causes an infinite loop, something we’ll revisit in the common mistakes section.
You could also write this using a do-while loop, which is useful when you want the multiplication to happen at least once before the condition is checked — though for factorial, the difference rarely matters in practice since n is almost always ≥ 1.
Factorial Program in C Using Recursion
Recursion is where the factorial program really shines as a teaching tool, because the mathematical definition of factorial — n! = n × (n-1)! — is already recursive. This makes it one of the cleanest introductions to recursion in C, alongside problems like Fibonacci series and Tower of Hanoi.
Recursive Factorial Function
#include <stdio.h>
long long factorial(int n) {
if (n == 0 || n == 1) { // base case
return 1;
}
return n * factorial(n - 1); // recursive case
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
if (n < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
printf("Factorial of %d is %lld\n", n, factorial(n));
}
return 0;
}
Output:
Enter a number: 5
Factorial of 5 is 120
How Recursion Works
Every recursive function needs two things: a base case (a condition that stops the recursion) and a recursive case (where the function calls itself with a smaller input). For factorial:
- Base case:
factorial(0) = 1andfactorial(1) = 1 - Recursive case:
factorial(n) = n × factorial(n - 1)
Here’s how the calls unfold for factorial(5):
factorial(5)
= 5 * factorial(4)
= 5 * (4 * factorial(3))
= 5 * (4 * (3 * factorial(2)))
= 5 * (4 * (3 * (2 * factorial(1))))
= 5 * (4 * (3 * (2 * 1)))
= 5 * 4 * 3 * 2 * 1
= 120
Each call to factorial() is pushed onto the call stack and waits there until the base case (factorial(1)) returns. Once that happens, the calls “unwind” back up the stack, multiplying their way to the final answer. This is exactly why recursion without a proper base case leads to a stack overflow — the function keeps calling itself with no way to stop.
Factorial Program in C Using Function
Whether you use a loop or recursion, it’s good practice to move the factorial logic into its own function rather than cramming everything into main(). This makes your code reusable — you can call factorial() multiple times for different values without repeating logic, which is especially useful in interview settings or larger programs from Codegnan’s C programming course.
#include <stdio.h>
long long factorial(int n) {
long long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (num < 0) {
printf("Invalid input. Factorial is not defined for negative numbers.\n");
return 1;
}
printf("Factorial of %d = %lld\n", num, factorial(num));
return 0;
}
Output:
Enter a number: 4
Factorial of 4 = 24
This version uses an iterative function (a loop inside a function) rather than recursion, giving you the best of both worlds — modular, reusable code without the overhead of recursive function calls.
Factorial Using Recursion vs Loop
Both approaches give the same result, but they behave very differently under the hood. Here’s a side-by-side comparison:
| Aspect | Loop (Iterative) | Recursion |
|---|---|---|
| Logic | Uses for/while to multiply numbers |
Function calls itself with n-1 |
| Readability | Simple, easy to trace | Elegant, mirrors the math formula |
| Memory usage | Constant — O(1) extra space | Grows with n — O(n) stack space |
| Speed | Generally faster | Slightly slower due to function call overhead |
| Risk | Infinite loop if increment is missed | Stack overflow if base case is missing |
| Best for | Large inputs, performance-critical code | Teaching recursion, small inputs |
In practice, most production C code favors the iterative version for performance and memory reasons — a pattern that holds true across many recursive problems, including the prime number checks you’ll encounter later in your C programming journey. Recursion is still worth mastering, though, since it forms the foundation for more advanced topics like tree traversal, divide-and-conquer algorithms, and dynamic programming.
Factorial Program in C Without Recursion
If you specifically want to avoid recursion — say, because your compiler has a limited stack size, or your instructor has asked for a non-recursive solution — simply use either of the loop-based versions covered earlier: the for loop method or the while loop method. Both are functionally identical to the recursive version but avoid the function-call stack entirely.
Here’s a compact, non-recursive version for quick reference:
#include <stdio.h>
int main() {
int n;
unsigned long long fact = 1;
printf("Enter a number: ");
scanf("%d", &n);
if (n < 0) {
printf("Factorial does not exist for negative numbers.\n");
return 1;
}
for (int i = 1; i <= n; i++) {
fact *= i;
}
printf("%d! = %llu\n", n, fact);
return 0;
}
Output:
Enter a number: 8
8! = 40320
This non-recursive approach is generally recommended for beginners and for any code where performance and predictable memory usage matter.
Factorial of Large Numbers in C
Here’s where things get interesting. Standard C data types have fixed sizes, which means they can only hold numbers up to a certain limit:
| Data Type | Typical Size | Approximate Max Value |
|---|---|---|
int |
4 bytes | ~2.1 billion |
unsigned int |
4 bytes | ~4.2 billion |
long long |
8 bytes | ~9.2 × 10¹⁸ |
unsigned long long |
8 bytes | ~1.8 × 10¹⁹ |
The problem is that factorials grow so fast that even long long runs out of room quickly. 20! is already 2,432,902,008,176,640,000 — right at the edge of what unsigned long long can hold. Try to calculate 21! or higher with a normal data type, and you’ll get integer overflow, producing an incorrect (often negative or garbage) result instead of an error.
#include <stdio.h>
int main() {
int n = 25;
unsigned long long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
printf("25! = %llu\n", fact); // This will be WRONG due to overflow
return 0;
}
Output (incorrect due to overflow):
25! = 7034535277573963776
The real value of 25! is 15,511,210,043,330,985,984,000,000 — nowhere close to what was printed. To calculate factorials of large numbers (say, above 20) correctly, you need to store the result as an array of digits and perform digit-by-digit multiplication manually, similar to how you’d multiply large numbers on paper.
#include <stdio.h>
#define MAX 500
int multiply(int x, int res[], int res_size);
void factorial(int n) {
int res[MAX];
res[0] = 1;
int res_size = 1;
for (int x = 2; x <= n; x++) {
res_size = multiply(x, res, res_size);
}
printf("Factorial of %d = ", n);
for (int i = res_size - 1; i >= 0; i--) {
printf("%d", res[i]);
}
printf("\n");
}
int multiply(int x, int res[], int res_size) {
int carry = 0;
for (int i = 0; i < res_size; i++) {
int prod = res[i] * x + carry;
res[i] = prod % 10;
carry = prod / 10;
}
while (carry) {
res[res_size] = carry % 10;
carry /= 10;
res_size++;
}
return res_size;
}
int main() {
factorial(30);
return 0;
}
Output:
Factorial of 30 = 265252859812191058636308480000000
This technique — storing large numbers digit by digit in an array — is a common building block in competitive programming and is worth practicing alongside other C language projects that deal with big-number arithmetic.
Factorial of Negative Numbers
Mathematically, factorial is not defined for negative numbers. The factorial formula relies on counting down from n to 1, and that sequence simply doesn’t exist for negative integers — you can’t multiply “5, 4, 3, 2, 1, 0, -1, -2…” down to any meaningful base case, because there’s no natural stopping point.
This is why every well-written factorial program in C should include an explicit check for negative input:
if (n < 0) {
printf("Factorial is not defined for negative numbers.\n");
}
If you skip this check in the recursive version, the consequences are worse than a wrong answer — the function will call itself endlessly (factorial(-1) calls factorial(-2), which calls factorial(-3), and so on), since it never hits the base case of n == 0 or n == 1. This eventually crashes the program with a stack overflow error. Always validate input before starting the calculation — a good habit to carry into every C program you write, not just this one.
(Note: In advanced mathematics, the concept is extended using the Gamma function, which can technically evaluate factorial-like values for non-integers and some negative numbers — but this is outside the scope of standard integer factorial in C and isn’t something you need for typical programming exercises.)
Common Mistakes in Factorial Programs in C
Even though the factorial program is simple, beginners tend to run into the same handful of bugs. Here’s what to watch out for:
- Initializing
factorialto0instead of1. Since factorial involves multiplication, starting with0makes every result0(anything multiplied by0is0). Always initialize to1. - Using
intinstead oflong longfor the result. Even moderate inputs liken = 15will overflow a regularint. Uselong longorunsigned long longfor safer results, and use the big-number technique for anything above20. - Forgetting the base case in recursion. Without
if (n == 0 || n == 1) return 1;, the recursive function never stops, leading to a stack overflow. - Forgetting to increment the loop counter in a
whileloop. If you forgeti++inside awhileloop, the conditioni <= nnever becomes false, and the program hangs in an infinite loop. - Not validating negative input. As discussed above, skipping the negative-number check can cause incorrect output (loop version) or a crash (recursive version).
- Mismatched format specifiers in
printf. Using%dto print along longvalue causes undefined behavior on many systems. Always match%lldwithlong longand%lluwithunsigned long long. - Confusing
0!with an error. Many beginners assume0!should throw an error or equal0. Mathematically,0! = 1by definition — make sure your base case reflects this.
Avoiding these pitfalls will save you a lot of debugging time, not just on this program but on other loop- and recursion-based problems you’ll write throughout your C programming syllabus.
Time and Space Complexity
Understanding the complexity of your factorial program is useful both for interviews and for building good coding habits early.
| Approach | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
| Iterative (for/while loop) | O(n) | O(1) | Constant extra space; only a few variables used |
| Recursive | O(n) | O(n) | Each call adds a frame to the call stack |
| Big-number (array-based) | O(n × d) | O(d) | d = number of digits in the result, which itself grows with n |
For the standard loop and recursive versions, the time complexity is O(n) in both cases — the multiplication is performed exactly n times either way. The difference lies in space complexity: the iterative version uses a fixed, constant amount of memory (O(1)), while the recursive version consumes stack space proportional to n (O(n)), since each recursive call remains on the stack until the base case is reached.
This is precisely why, for large values of n, the iterative approach is preferred in real-world code — a principle that applies broadly across recursive problems in C, not just factorial. If you want to build a deeper intuition for how complexity scales with input size, it’s worth practicing this analysis on related problems like Fibonacci series in C and prime-checking algorithms, where the difference between O(n) and O(n²) approaches becomes even more visible.
Frequently Asked Questions
What is factorial in C?
Factorial in C refers to a program that calculates the product of all positive integers from 1 up to a given number n, denoted as n!. It’s typically implemented using a loop or a recursive function and is one of the most common beginner exercises for practicing control flow and recursion in C.
How do you write a factorial program in C?
You write a factorial program in C by declaring an integer variable to store the input, initializing a result variable to 1, and then multiplying that result by every integer from 1 to n — either inside a for/while loop or through a recursive function. Don’t forget to check for negative input and use a data type like long long to avoid overflow for larger values.
How do you find factorial using a for loop?
To find factorial using a for loop, initialize a variable fact = 1, then loop from i = 1 to i <= n, multiplying fact = fact * i on each iteration. After the loop finishes, fact holds the factorial of n. See the full factorial program using a for loop above for the complete code.
How do you find factorial using recursion?
To find factorial using recursion, define a function with a base case of factorial(0) = 1 (or factorial(1) = 1) and a recursive case of factorial(n) = n * factorial(n - 1). The function keeps calling itself with a smaller value of n until it hits the base case, then multiplies its way back up to produce the final result. Full code is available in the recursive factorial function section above.
What is 0 factorial?
0! (zero factorial) is defined as 1. This isn’t calculated through multiplication — it’s a mathematical convention that makes formulas involving permutations and combinations work correctly. In code, this is why the base case for recursive factorial functions checks for both n == 0 and n == 1.
Can factorial be calculated for negative numbers?
No. Factorial is mathematically undefined for negative integers, since there’s no valid sequence of positive integers to multiply down to a base case. A well-written C program should check for negative input and display an error message rather than attempting the calculation — see the negative numbers section above for details and sample code.
What is the time complexity?
Both the iterative (loop-based) and recursive versions of the factorial program have a time complexity of O(n), since the multiplication operation is performed n times regardless of the method. The key difference is in space complexity: the iterative version uses O(1) space, while the recursive version uses O(n) space due to the function call stack. For a full comparison, see the time and space complexity table above.
Want to strengthen your C fundamentals beyond factorial? Explore more hands-on problems in Codegnan’s C language projects, check the complete C programming syllabus, or browse more logic-building guides like Fibonacci series in C and prime number program in C on the Codegnan blog.




