Factorial program in C | C Program to Find Factorial of a Number

Factorial program in C | C Program to Find Factorial of a Number

Factorial program in C | C Program to Find Factorial of a Number

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"
  11. ,number,fact); 
  12. return 0;  
  13. }   

Output:

Enter a number: 5
Factorial of 5 is: 120


Factorial Program using recursion in C

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

Output:

Enter a number: 6
Factorial of 5 is: 720

factorial program in c using while loop

  1. #include <stdio.h>
  2. int main()
  3. {
  4.  int n,i,f;
  5.  f=i=1;
  6. printf("Enter a Number to Find Factorial: ");
  7. scanf("%d",&n);
  8.  while(i<=n)
  9. {
  10. f*=i;
  11. i++;
  12.  }
  13. printf("The Factorial of %d is : %d",n,f);
  14. return 0;
  15. }

Output:

Enter a Number to Find Factorial: 5
The Factorial of 5 is : 120

factorial program in c using function

  1. #include <stdio.h>
  2. long factorial(int);
  3. int main()
  4. {
  5.   int n;
  6.   printf("Enter a number to calculate 
  7. its factorial\n");
  8.   scanf("%d", &n);
  9.   printf("%d! = %ld\n", 
  10. n, factorial(n));
  11.   return 0;
  12. }
  13. long factorial(int n)
  14. {
  15.   int c;
  16.   long r = 1;
  17.   for (c = 1; c <= n; c++)
  18.     r = r * c;
  19.   return r;
  20. }

Output:

Enter a Number to Find Factorial: 5
The Factorial of 5 is : 120

factorial program in c using function

  • Factorial Program in C
  • Factorial Program using loop
  • Factorial Program using recursion in C
  • factorial program in c using while loop
  • C Program for Factorial Using Ternary Operator
Next Post Previous Post
No Comment
Add Comment
comment url