In this tutorial, we are going to learn How to find Factorial of any number in the C language
What is the factorial of a number?
In mathematics, We can say that the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n
For example,
4! = 4*3*2*1 = 24
6! = 6*5*4*3*2*1 = 720
Here, 4! is pronounced as “4 factorial”,
The factorial is normally used in Combinations or we can say in other word is mathematics
There are different ways to write the factorial program in c language program. we can see the 3 ways to write the factorial(!) program.
1.Using for loop
2.Using while loop
3.Using Recursion
1.Using for loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <stdio.h> int main() { int number; int fact = 1; printf("Enter zero(O) or Positive number:\n"); scanf("%d",&number); if(number >=0){ printf("Finding Factorial of %d\n",number); for(int i = 1 ; i<=number;i++){ fact = fact*i; } printf("Factorial of %d = %d",number,fact); }else{ printf("Please enter either 0 or positive number"); } return 0; } |
The output of the above program :
5
Finding Factorial of 5
Factorial of 5 = 120
2.Using while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <stdio.h> int main() { int n,x, f=1; //Taking input from User printf("Enter a Number :"); scanf("%d",&n); //Storing Input number in variable x x = n; //Validation for invalid input if(n < 0){ printf("Enter valid Number Input number should be either zero or a positive number"); exit(0); } //Logic to find Factorial of input Number while(n>=1){ f=f*n; n--; } //Printing Input Number and it's factorial value printf("Factorial of %d is %d",x,f); return 0; } |
Few Input & output of the above program:
Enter a Number :0
Factorial of 0 is 1
Enter a Number:5
Factorial of 5 is 120
Enter a Number:-3
Enter valid Number Input number should be either zero or a positive number
3.Using recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include<stdio.h> int fact(int n); int main() { int n; //Taking input from User printf("Enter a Number : "); scanf("%d",&n); printf("Factorial of %d is %ld", n, fact(n)); return 0; } int fact(int n) //Logic to find Factorial of input Number { if (n>=1) return n*fact( n-1); else return 1; } |
The output of the above program :
Enter a Number: 6
Factorial of 6 is 720
In this post, we learned about How to find Factorial of any number in the C language
You May Also Like:
Swapping of two numbers in C Language by using a temporary variable
Thank you for visiting.
If you have any feedback or suggestion please drop in below the comment box.