Factorial Program in C

Factorial Program
 in C: Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!. For example:

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

Here, 5! is pronounced as "5 factorial", it is also called "5 bang" or "5 shriek".

The factorial is normally used in Combinations and Permutations (mathematics).

There are many ways to write the factorial program in c language. Let's see the 2 ways to write the factorial program.

  • Factorial Program using loop
  • Factorial Program using recursion

Factorial Program using loop

Let's see the factorial Program using loop.

  1. #include<stdio.h>  
  2. int main()    
  3. {    
  4.  int i,fact=1,number;    
  5.  printf("Enter a number: ");    
  6.   scanf("%d",&number);    
  7.     for(i=1;i<=number;i++){    
  8.       fact=fact*i;    
  9.   }    
  10.   printf("Factorial of %d is: %d",number,fact);    
  11. return 0;  
  12. }   

Output:

Enter a number: 5
Factorial of 5 is: 120

Factorial Program using recursion in C

Let's see the factorial program in c using recursion.

  1. #include<stdio.h>  
  2.   
  3. long factorial(int n)  
  4. {  
  5.   if (n == 0)  
  6.     return 1;  
  7.   else  
  8.     return(n * factorial(n-1));  
  9. }  
  10.    
  11. void main()  
  12. {  
  13.   int number;  
  14.   long fact;  
  15.   printf("Enter a number: ");  
  16.   scanf("%d", &number);   
  17.    
  18.   fact = factorial(number);  
  19.   printf("Factorial of %d is %ld\n", number, fact);  
  20.   return 0;  
  21. }  

Output:

Enter a number: 6 
Factorial of 6 is: 720 
Previous Post Next Post