Description:
This program calculates the factorial of a number. Factorial is a basic concept in mathematics where the product of all positive integers up to a number is calculated. It uses a for
loop to perform repeated multiplication and also demonstrates how to handle errors for invalid inputs (negative numbers).
Usage:
The user inputs a positive integer, and the program calculates and displays its factorial.
Code:
C
#include <stdio.h>
int main() {
int num, i;
unsigned long long factorial = 1;
// Asking user to input an integer
printf("Enter an integer: ");
scanf("%d", &num);
// Error handling for negative numbers
if (num < 0) {
printf("Error! Factorial of a negative number doesn't exist.\n");
} else {
for (i = 1; i <= num; ++i) {
factorial *= i; // Multiplying the numbers from 1 to num
}
printf("Factorial of %d = %llu\n", num, factorial);
}
return 0;
}
Explanation:
- The program calculates the factorial of a number by multiplying it with all numbers less than or equal to it.
- Factorial is calculated only for non-negative integers.
Test here: