Factorial program in C

Factorial program in C
Factorial program in C

Problem Statement: Given a number N, find the factorial of the number. Factorial program in C.


Example 1:
Input: N = 4
Output: 24
Explanation: 4*3*2*1 = 24

Example 2:
Input: N = 5
Output: 120
Explanation: 5*4*3*2*1 = 120

DisclaimerDon’t jump directly to the solution, try it out yourself first.

What is factorial of a number?

Factorial of a number is defined as the product of all positive numbers less than or equals to that number. As given in the above examples, factorial of 4 will be product of all numbers less than or equal to 4. That is, 1,2,3,4.

Therefore, factorial of 4 = 1*2*3*4 = 24.

In mathematics, factorial is defined by the sign “!”. That is, factorial of 4 will be denoted as “4!”


We will run a loop from 1 to the given number and multiply each number in that range then the resultant product is our factorial.


C Program

#include <stdio.h>

int factorial(int n) {
   int ans = 1;
   for (int i = 1; i <= n; i++) {
      ans = ans * i;
   return ans;
int main() {
   int n = 5;
   int result = factorial(n);
   printf("The factorial of %d is %d",n,result);

Output: The factorial of 5 is 120

Time Complexity: O(n)

Space Complexity: O(1)

Special thanks to Subhrajit Das for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article