#include <stdio.h> // Include the standard input-output header
// Function to calculate factorial
int factorial(int n) {
int i, p = 1; // Initialize p to 1, which will hold the factorial value
// Loop from n down to 2
for (i = n; i > 1; i--) {
p *= i; // Multiply p by i at each step
}
return p; // Return the calculated factorial
}
int main() {
int a, result; // Declare variables for input number and the result
// Ask the user to input a number
printf("Enter an integer number: ");
scanf("%d", &a);
// Calculate factorial by calling the factorial function
result = factorial(a);
// Display the result
printf("The factorial of %d is %d.\n", a, result);
return 0; // Return 0 to indicate successful execution
}
Explanation:
Function Declaration (
factorial
): Thefactorial
function takes an integern
as an argument and calculates its factorial using afor
loop. It multiplies the variablep
with each number starting fromn
down to2
and returns the result.Main Function:
- It asks the user for an integer input.
- The factorial is calculated using the
factorial
function. - The result is printed to the screen.
Sample Input/Output:
Input:
Enter an integer number: 5
Output:
The factorial of 5 is 120.