Published: 13 November 2025
Reading Time: 6 minutes
Source: NxtWave CCBP Blog
In mathematics, factorial is the product of all the positive integers that are less than or equal to the number whose factorial is required. For example, the factorial of 5 is written as:
5! = 5 × 4 × 3 × 2 × 1 = 120
Factorials have important applications in:
This article provides a comprehensive look at writing factorial programs in C, covering multiple implementation approaches with detailed code examples.
A factorial program in C is code that performs the multiplication required to find the factorial of a number. In C, this can be accomplished using several techniques:
Data Types: Variables must be declared with appropriate data types to store numbers:
int - Integer valuesfloat - Floating-point numberschar - Character valuesdouble - Double-precision floating-pointunsigned long long - Large positive integersOperators Used:
Control Structures:
Here is the general algorithm for a C program to find the factorial of a number:
Key Point: The factorial algorithm is direct: initialize, iterate, multiply sequentially, and print the result.
Proper input and output handling is crucial for any C program. In factorial programs, this involves prompting the user, reading input, and displaying results.
The program typically starts in the main() function with variable declarations:
int variable to store the user's input numberunsigned long long variable for the factorial result (especially for large outputs)printf() Function:
printf("Enter a number: ");scanf() Function:
scanf("%d", &n);Important to include validation for negative numbers:
if statement to check for negative input#include <stdio.h>
int main() {
int n;
unsigned long long factorial = 1;
printf("Enter an integer: "); // prompt message
scanf("%d", &n); // reading input
// error handling for negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for (int i = 1; i <= n; ++i) {
// for loop
factorial *= i;
}
printf("Factorial of %d = %llu", n, factorial); // printing result
}
return 0;
}
printf() displays messages; scanf() reads user input safely into variablesThe for loop is a frequently used method in C for calculating a number's factorial. The program runs a block of code repeatedly and multiplies the result variable by the loop counter at each step.
The loop continues from 1 to the input number until it produces the factorial value.
// C program to Find the Factorial Using for Loop
#include <stdio.h>
unsigned int factorial(unsigned int N) {
int fact = 1, i;
// Loop from 1 to N to get the factorial
for (i = 1; i <= N; i++) {
fact *= i;
}
return fact;
}
int main() {
int N = 5;
int fact = factorial(N);
printf("Factorial of %d is %d", N, fact);
return 0;
}
Factorial of 5 is 120
A factorial program in C using a while loop repeatedly multiplies numbers from 1 up to the given input. The loop runs as long as the counter is less than or equal to the input number.
Each iteration updates the factorial result, making it an effective way to calculate factorials iteratively.
#include<stdio.h>
int main() {
int number, factorial = 1;
printf("Enter a number: ");
scanf("%d", &number);
while(number > 1) {
factorial = factorial * number;
number--;
}
printf("Factorial is: %d", factorial);
return 0;
}
In the recursive approach, a function calls itself to solve smaller subproblems of the original problem. Each recursive call breaks the problem into simpler parts and works towards a base case.
The base case defines the stopping condition. In factorial calculation:
The factorial function keeps calling itself with number - 1 as long as the number is 1 or greater. Each recursive call multiplies the current number by factorial(number - 1). When the number becomes less than 1, the function stops and returns 1.
#include<stdio.h>
long int factorial(int number) {
if(number >= 1)
return number*factorial(number-1);
else
return 1;
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("Factorial of %d is: %ld", number, factorial(number));
return 0;
}
A factorial program in C can use arrays to handle very large numbers. Arrays store individual digits of the factorial result, allowing calculations that go beyond the usual integer limits.
Standard data types have limits:
int typically stores up to 2,147,483,647long long has larger but still finite limitsMultiplication is done digit by digit, and results are saved in the array. This method is efficient for calculating factorials of extremely large numbers.
#include <stdio.h>
#include <string.h>
// Function to multiply a string (representing a number)
// by an integer
void multiplyString(char num[], int factor) {
int len = strlen(num);
int carry = 0;
for (int i = len - 1; i >= 0; i--) {
int digit = num[i] - '0';
int product = digit * factor + carry;
num[i] = (product % 10) + '0';
carry = product / 10;
}
// Handling the carry by adding digits to the front
// of the number
while (carry) {
for (int i = strlen(num); i >= 0; i--) {
num[i + 1] = num[i];
}
num[0] = (carry % 10) + '0';
carry /= 10;
}
}
// Function to find factorial using a string
void factorialString(int N) {
// Use a large enough buffer
char fact[1000];
// Initialize result as "1"
strcpy(fact, "1");
for (int i = 2; i <= N; i++) {
// Multiply the string in each iteration
multiplyString(fact, i);
}
printf("Factorial of %d is %s", N, fact);
}
int main() {
int N = 5;
factorialString(N);
return 0;
}
A factorial program in C can be designed with minimal statements by using the ternary operator. The ternary operator behaves as a compact conditional, checking whether the number is less than or equal to one (base case returns 1), otherwise it multiplies the number by the factorial of one less number recursively.
The ternary operator format: condition ? value_if_true : value_if_false
#include<stdio.h>
long int factorial(int number) {
return (number >= 1) ? number*factorial(number-1) : 1;
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("Factorial of %d is: %ld", number, factorial(number));
return 0;
}
Key Point: The ternary operator provides concise, elegant syntax for recursive factorial implementation.
The factorial series program calculates the factorials of numbers from 0 up to a given number. The program uses a loop to calculate the factorials of each number in sequence and displays them.
Another loop or recursion is used within the main loop to calculate individual factorials, which are then stored and displayed in sequence.
#include<stdio.h>
long int factorial(int number) {
long int fact = 1;
for(int i = 1; i <= number; i++) {
fact = fact * i;
}
return fact;
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
for(int i = 0; i <= number; i++) {
printf("Factorial of %d is: %ld\n", i, factorial(i));
}
return 0;
}
If user enters 5:
Factorial of 0 is: 1
Factorial of 1 is: 1
Factorial of 2 is: 2
Factorial of 3 is: 6
Factorial of 4 is: 24
Factorial of 5 is: 120
Writing a factorial program in C is a valuable initial programming exercise that provides good knowledge and strengthens problem-solving skills. It helps learners appreciate various control structures such as:
You can make errors here and learn from them to advance to higher-level code. Moreover, understanding factorial logic builds a foundation for tackling more advanced algorithms and mathematical problems in programming.
Understanding factorial programs is a great way for learners to build their confidence in:
It demonstrates how iterative and recursive logic can be used to solve complex problems efficiently. Proficiency in factorials is essentially the starting point for dealing with algorithms that include:
A factorial of a number is the result of multiplying all positive whole numbers from 1 up to that number. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
Recursion involves a function calling itself with a reduced number. It multiplies the result until it reaches the base case, which is usually 1. The recursion ends once it reaches that base case.
For very large factorials, you can use arrays. Arrays can store individual digits or libraries designed for big-number calculations and get the results.
A loop repeatedly executes a block of code until the factorial is arrived at. Recursion calls the function within itself. Both methods yield the same result but use different approaches.
If you are looking for efficiency, using iterative methods like loops is more memory-efficient than recursion. Additionally, storing previously computed results can speed up the process for large numbers.
About NxtWave: NxtWave provides comprehensive programming education and career development resources for students and professionals. Contact: [email protected] | WhatsApp: +919390111761
Source: This content is from NxtWave CCBP Blog - https://www.ccbp.in/blog/articles/factorial-program-in-c