In Mathematics factorial, is an operation that calculates the product of all positive integers less than or equal to the given number.
![](https://gangforcode.com/wp-content/uploads/2023/11/C-Code-for-Factorial.jpg)
Table of Contents
Here we are going to see how we can calculate the factorial of a given number in C programming language.
We can calculate the factorial of a given number either by using a loop or by using recursion.
C Code for Factorial Using Loop
#include <stdio.h>
void main()
{
int n, fact = 1, i = 0;
printf("Enter the Nmber");
scanf("%d", &n);
if (n < 0)
{
printf("Invalid Input");
}
else if (n == 0)
{
printf("Factorial of %d = 1", n);
}
else
{
for (i = 1; i <= n; i++)
{
fact = fact * i;
}
printf("Factorial of %d = %d", n, fact);
}
}
Output
![c code for factorial using loop](https://thecodedata.com/wp-content/uploads/2023/11/image-1.png)
C Code for Factorial Using Recursion
#include <stdio.h>
int factorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}
void main()
{
int n, fact = 1, i = 0;
printf("Enter the Number");
scanf("%d", &n);
if (n < 0)
{
printf("Invalid Input");
}
else
{
fact = factorial(n);
printf("Factorial of %d = %d", n, fact);
}
}
Output
![c factorial using recursion](https://thecodedata.com/wp-content/uploads/2023/11/image-2-1024x124.png)
The above C code calculates factorial by calling a recursive function factorial()
this function takes number as a input and return number of the factorial.
10 thoughts on “C Code for Factorial”