top of page

C | Factorial program

In this post, we will learn how to find the factorial of a given number. This is the most asked interview question so grasp it properly.

  1. 5! = 5*4*3*2*1 = 120  

  2. 3! = 3*2*1 = 6  

Here, 5! is pronounced as "5 factorial".


Implementation using a loop :

#include<stdio.h> 
int main()    
{    
 int i,fact=1,number;    
 printf("Enter a number: ");    
  scanf("%d",&number);    
 for(i=1;i<=number;i++){    
      fact=fact*i;    
  }    
  printf("Factorial of %d is: %d",number,fact);    
return 0;  
}   

Output :

Enter a number: 5
Factorial of 5 is: 120

Implementation using recursion :

#include<stdio.h> 
 
long factorial(int n)  
{  
 if (n == 0)  
 return 1;  
 else 
 return(n * factorial(n-1));  
}  
 
void main()  
{  
 int number;  
 long fact;  
  printf("Enter a number: ");  
  scanf("%d", &number);   
 
  fact = factorial(number);  
  printf("Factorial of %d is %ld\n", number, fact);  
 return 0;  
}  

Output :

Enter a number: 6
Factorial of 5 is: 720 
 

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor

Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

17 views0 comments

Recent Posts

See All
bottom of page