Factorial Program in C

Factorial Program in C

Factorial Program in C: Factorial of n is the result of all positive diving numbers. Factorial of n is indicated 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. #include<conio.h>  
  3. void main(){  
  4.   int i,fact=1,number;  
  5.   clrscr();  
  6.   printf(“Enter a number: “);  
  7.   scanf(“%d”,&number);  
  8.   
  9.   for(i=1;i<=number;i++){  
  10.       fact=fact*i;  
  11.   }  
  12.   printf(“Factorial of %d is: %d”,number,fact);  
  13.   getch();  
  14. }  
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. #include<conio.h>  
  3.   
  4. long factorial(int n)  
  5. {  
  6.   if (n == 0)  
  7.     return 1;  
  8.   else  
  9.     return(n * factorial(n-1));  
  10. }  
  11.    
  12. void main()  
  13. {  
  14.   int number;  
  15.   long fact;  
  16.   clrscr();  
  17.   printf(“Enter a number: “);  
  18.   scanf(“%d”, &number);   
  19.    
  20.   fact = factorial(number);  
  21.   printf(“Factorial of %d is %ldn”, number, fact);  
  22.   getch();  
  23. }  
Output:
Enter a number: 6
Factorial of 5 is: 720

Leave a Reply

Your email address will not be published. Required fields are marked *