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.
Code
Here is an example of how the program could be implemented:
C
#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;
}
Output
Output
Enter an integer: 5
Factorial of 5 = 120
It's Working
- The first line,
#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. - The int main() line defines the main function of the program. This is the entry point of the program, and the code within the curly braces ({}) will be executed when the program runs.
- In the next line, we declared 2 variables
n
andi
. We initialized the factorial variable with 1. - Then we take the input for the number(
n
) from the user usingscanf()
function. - We use an if-else statement to check if the input number is negative, if it is then it will show an error message "Error! Factorial of a negative number doesn't exist."
- Otherwise, We use a for loop to calculate the factorial of the given number. The loop runs from 1 to n and each time the loop variable is multiplied by the factorial variable.
- Finally, we print the factorial of the given number using the
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.