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.
5! = 5*4*3*2*1 = 120 Â
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.