Introduction
In this blog, we will discuss the problem of calculating the factorial of a number. We will code the solution to this problem in C language. We will discuss two different approaches to solve this problem. But before discussing the different solutions to this problem, we should first look at a factorial of a number and how we can calculate the factorial of a number.
Also see, Binary to Hex Converter and C Static Function.
What is Factorial of a number?
Factorial of a number can be defined as the product of all the numbers less than or equal to the given number. If there is a number n, its factorial can be represented as n!. For example, if we need to calculate the factorial of the number 5, we will represent the factorial of 5 as 5!. There is a universal fact that

Now, let us look at the formula with which we can calculate the factorial of a number,

Sample Examples
Example 1:
Input:
N = 6
Output:
720
Explanation:
6! = 6 x 5 x 4 x 3 x 2 x 1 = 720
Example 2:
Input:
N = 8
Output:
40320
Explanation:
8! = 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 40320
You can also read about dynamic array in c, And Tribonacci Series
Iterative Method
- In this approach, we will calculate the factorial of a number using a for a loop. First, we will declare a variable named n and a variable named fact which will be of long data type.
- Let us suppose that value of n is equal to 4. Then, we will start the for loop from 1 till 4, and we will keep multiplying the numbers. Simultaneously we will store the result in the variable fact.
- We will print the result variable when the loop ends, i.e., fact.
Implementation in C++
// C program to calculate the factorial of a number
#include <stdio.h>
int main()
{
long int n, fact = 1;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
fact = fact * i;
}
printf("Factorial of %d is equal to %d", n, fact);
return 0;
}
Output:
Input: N = 7
Output: Factorial of 7 is equal to 5040
Complexity Analysis
Time Complexity: O(N)
Since we are traversing a for loop from 1 to n, the complexity would be O(N).
Space Complexity: O(1)