Calculating the factorial of a number is one of the most popular exercises for beginners learning C programming. The factorial of a number is defined as the product of all positive integers from 1 up to that number. For example, the factorial of 5, written as 5!, is equal to 5 × 4 × 3 × 2 × 1 = 120. This concept not only helps strengthen mathematical logic but also introduces important programming ideas like loops, iteration, and variable manipulation.
In C, factorial programs are often used to explain how loops work because the calculation requires repeated multiplication. Instead of writing several multiplication statements, loops allow us to perform this process efficiently, regardless of the size of the number. This tutorial will guide you through writing a C program that calculates the factorial of a number using loops. We will explain the code line by line, show common mistakes to avoid, and answer common beginner questions.
Understanding Factorial in Programming
Before moving to the code, let’s first understand the concept. If a number n
is given, then:
Factorial (n) = n × (n-1) × (n-2) × … × 1
This means factorial grows very quickly as n
increases. For example, 6! = 720 and 10! = 3,628,800. Because factorial values get large, we must also be careful about which data type to use in C. For small values of n
, int
is enough, but for larger values, long long int
is safer.
C Program to Calculate Factorial Using a For Loop
Let us first see how to calculate factorial using a for
loop.
#include <stdio.h>
int main() {
int n, i;
long long factorial = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
factorial *= i;
}
printf("Factorial of %d = %lld\n", n, factorial);
return 0;
}
In this program, we begin by including the stdio.h
library, which allows us to use input and output functions like printf
and scanf
. The variable n
stores the number whose factorial we want to find, and factorial
is initialized as 1 because multiplying by 1 does not affect the result.
The user is asked to input a positive integer. Then, a for
loop is used to multiply factorial
by each number from 1 up to n
. For example, if n = 5
, the loop executes five times: factorial becomes 1 × 1 = 1, then 1 × 2 = 2, then 2 × 3 = 6, then 6 × 4 = 24, and finally 24 × 5 = 120. Once the loop finishes, the final value of factorial is displayed.
C Program to Calculate Factorial Using a While Loop
The same logic can be implemented with a while
loop, which may be easier for some learners to understand.
#include <stdio.h>
int main() {
int n, i = 1;
long long factorial = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
while (i <= n) {
factorial *= i;
i++;
}
printf("Factorial of %d = %lld\n", n, factorial);
return 0;
}
Here, the loop starts with i = 1
and continues until i
becomes greater than n
. In each iteration, the value of i
is multiplied with factorial
, and then i
is increased by one. This continues until all numbers up to n
are multiplied. The output is the same as the for
loop method, but the structure of the loop is slightly different.
C Program to Calculate Factorial Using Recursion
Although the title of this tutorial focuses on loops, it is helpful to also see how factorial can be calculated using recursion. Recursion means that a function calls itself until a certain condition is met. In mathematics, factorial can be defined recursively as:
- n! = n × (n-1)! for n > 0
- 0! = 1
This makes recursion a natural choice for implementing factorial.
Here is the recursive C program:
#include <stdio.h>
long long factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n < 0)
printf("Factorial is not defined for negative numbers.\n");
else
printf("Factorial of %d = %lld\n", n, factorial(n));
return 0;
}
In this program, we define a function called factorial
that takes an integer n
. If n
equals 0, the function returns 1, which is the base case. Otherwise, the function returns n * factorial(n-1)
. Each call reduces the value of n
by 1, and the process continues until n
reaches 0.
For example, if n = 5
, the program computes factorial as:
factorial(5) = 5 × factorial(4)
factorial(4) = 4 × factorial(3)
factorial(3) = 3 × factorial(2)
factorial(2) = 2 × factorial(1)
factorial(1) = 1 × factorial(0)
factorial(0) = 1
When the base case is reached, all the results are multiplied step by step, producing the final answer of 120.
Comparing Loops and Recursion
Loops and recursion both solve the problem of factorial calculation. Loops are generally more efficient because they use less memory. Recursion, however, provides a cleaner and more mathematical way of writing the program, which can be easier to understand conceptually. For small numbers, both methods work fine. But for very large values of n
, recursion can cause a stack overflow, while loops are safer.
Common Beginner Mistakes
When writing factorial programs, beginners often make these mistakes:
- Forgetting to initialize the
factorial
variable to1
. Starting with0
will always give a result of zero, since any number multiplied by zero is zero. - Not handling negative numbers. Factorials are only defined for non-negative integers, so the program should reject negative input.
- Using the
int
data type for large values. This can cause overflow and incorrect results. A safer choice islong long int
to handle larger factorials.
To avoid these issues, always start factorial
at 1
, validate input, and choose a data type that can store the expected result.
FAQs
Q1: What is the factorial of 0?
The factorial of 0 is defined as 1. This is a special mathematical rule, and it is important to remember when writing programs.
Q2: Can factorial be calculated for negative numbers?
No, factorial is not defined for negative integers. If the user enters a negative number, the program should display a message saying it is invalid.
Q3: Which loop is better, for loop or while loop?
Both loops work the same way in this program. The for
loop is generally preferred because it is more compact and easier to read when the number of iterations is fixed.
Q4: Why use long long int
instead of int
?
Factorials grow very fast, and for numbers greater than 12, the result will exceed the range of int
. Using long long int
allows handling larger values safely.
Conclusion
The factorial program in C is an excellent example to practice loops, multiplication, and input-output operations. You can implement it using either a for
loop or a while
loop, and both methods give the same result. This problem teaches the importance of initialization, loop control, and correct use of data types. By practicing factorial programs, you will strengthen your logic-building skills and become more comfortable with C programming. Once you master this, you can explore recursion-based factorial programs to understand function calls.
References & Additional Resources
- Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language. 2nd Edition, Prentice Hall, 1988.
- GeeksforGeeks: Factorial Program in C – Different methods to find factorial.
- Programiz: C Factorial Examples – Beginner-friendly examples.
- TutorialsPoint: C Loops – Guide to loops in C programming.