C Program: Factorial of a Number
The factorial of a given positive integer $n$ is defined as the product of all whole numbers from 1 to $n$.
It is denoted by $n!$
$n! = n\times(n-1)\times ... \times1$
We calculate factorials only of positive integers, hence we specify the input number n
as of type unsigned short int
. The counter i
will also always be positive, hence it is also assigned to type unsigned short int
. The computed factorial factorial
again is always going to be a positive, hence, we define it to be of type unsigned long int
.
Also, note that $0! = 1$.
Below we write a C program which computes the factorial of a given number $n$.
#include <stdio.h>
int main() {
unsigned short int i, n;
unsigned long int factorial = 1;
printf("Enter a positive integer: ");
scanf("%hu", &n);
for(i = 1; i <=n; i++) {
factorial = factorial * i;
}
printf("Factorial of %hu is %lu \n", n, factorial);
return 0;
}
We run the program to compute $5!$ and get the output as shown below:
$ ./a.out
Enter a positive integer: 5
There is a powerful online computing engine called Wolfram Alpha which you can use for getting accurate factorials of big numbers.
Below we compute the factorial of 12.
We can also define a recursive function and call it to compute the required factorial as shown in the program below.
#include <stdio.h>
unsigned long factorial(unsigned short int);
int main() {
unsigned short int n;
printf("Enter a positive integer: ");
scanf("%hu", &n);
printf("Factorial of %hu is %lu", n, factorial(n));
return 0;
}
unsigned long factorial(unsigned short n) {
unsigned long f;
if(n == 0 || n == 1)
return 1;
else
f = n * factorial(n-1);
return f;
}