Factorial Calculation in C
This program calculates the factorial of a given number using the C programming language. The factorial of a non-negative integer n
is the product of all positive integers less than or equal to n
. It is denoted by n!
.
Program Explanation
The program uses a simple iterative approach to calculate the factorial. It multiplies all the integers from 1 up to the given number n
to get the factorial value.
C Program
#include <stdio.h>
/**
* Function to calculate the factorial of a given number.
*
* @param n The number for which the factorial is to be calculated.
* @return The factorial of the given number.
*/
long long factorial(int n) {
long long fact = 1;
for (int i = 1; i <= n; ++i) {
fact *= i;
}
return fact;
}
/**
* Main function to drive the program.
*/
int main() {
int number;
// Asking the user for input
printf("Enter a positive integer: ");
scanf("%d", &number);
// Checking for non-negative input
if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
// Calculating factorial and displaying the result
printf("Factorial of %d = %lld\n", number, factorial(number));
}
return 0;
}
Explanation of the Program
The program consists of the following components:
factorial
function: This function takes an integern
as input and returns the factorial ofn
. It initializes a variablefact
to 1 and iteratively multiplies it by each integer from 1 ton
.main
function: This is the entry point of the program. It prompts the user to enter a positive integer and checks if the input is non-negative. If the input is valid, it calls thefactorial
function and prints the result. If the input is negative, it displays an appropriate message.
This program provides a simple and clear way to understand the concept of calculating factorials in C, with adequate input validation to ensure correct results.