In this tutorial, we will learn how to write a C program to find the factorial of a given number. The factorial of a positive integer n is the product of all positive integers less than or equal to n. For example, the factorial of 5 is 5! = 5 x 4 x 3 x 2 x 1 = 120.
Here is an example of how the program could be implemented:
#include <stdio.h>
int main() {
int n, i;
int factorial = 1;
printf("Enter an integer: ");
scanf("%d", &n);
// show error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for (i = 1; i <= n; i++) {
factorial *= i;
}
printf("Factorial of %d = %d", n, factorial);
}
return 0;
}Enter an integer: 5
Factorial of 5 = 120#include <stdio.h>, is a preprocessor directive that tells the compiler to include the contents of the standard input/output header file (stdio.h) in the program.n and i. We initialized the factorial variable with 1.n) from the user using scanf() function.printf() function and return 0 from the main function.It's important to note that the type of variable that stores the factorial should be large enough to hold the largest possible factorial, if not the output will be truncated, In this case, we used int but you can use the unsigned long long type that is guaranteed to hold factorial up to 20.
This program will find the factorial of the given number, and print it on the screen.