C Program to find factorial of a number

In mathematics, the factorial of a positive integer n, denoted by n!, is the product of all positive integers less than or equal to n: n! = n x (n-1) x (n-2) x (n-3) x ... x 3 x 2 x 1. For example: 6! = 6*5*4*3*2*1 = 720 And the value of 0! is 1. This is the most common question asked in Technical interview or Coding round. There are many ways to solve this question some of them are discussed here: Recursive implementation using C: #include<stdio.h>

int factorial(int n)
{
if(n == 0)
return 1;
return n * factorial(n-1);
}
int main()
{
int number;
printf("Enter number : \n");
scanf("%d",&number);
printf("Factorial of %d is %d ",number,factorial(number));
return 0;
} Output:
Enter number :
5
Factorial of 5 is 120 Iterative Implementation using C: #include<stdio.h>

int factorial(int n)
{
if(n == 0 || n == 1)
return 1;
int fact=1, i;
for(i=2; i<=n; i++)
{
fact = fact * i;
}
return fact;
}
int main()
{
int number;
printf("Enter number : \n");
scanf("%d",&number);
printf("Factorial of %d is %d ",number,factorial(number));
return 0;
} Output:
Enter number :
5
Factorial of 5 is 120 Using ternary operator in C: #include<stdio.h>

int factorial(int n)
{
return (n == 1 || n == 0 ) ? 1 : n * factorial(n - 1);
}
int main()
{
int number;
printf("Enter number :\n");
scanf("%d",&number);
printf("Factorial of %d is %d ",number,factorial(number));
return 0;
} Output:
Enter number :
5
Factorial of 5 is 120 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Follow Programmers Door for more. #blog #interview #programming #c #factorial

        Contact Us

programmersdoor@gmail.com

  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door