Write a Program to Calculate the Factorial of a Number in C.
Definition of a Factorial:
The factorial of a number is the multiplication of all the numbers between 1 and the number itself. It is written like this: n!. So the factorial of 2 is 2! (= 1 × 2).
To Calculate a Factorial:
- 0! = 1
- n! = (n - 1)! × n
The factorial of 0 has value of 1, and the factorial of a number n is equal to the multiplication between the number n and the factorial of n-1.
Code:
/*Program to print given number of factorial*/ #include <stdio.h> int main() { int num; // Taking Input from the user printf("Enter a number: "); scanf("%d", &num); int product = 1; // Checking for negative input if (num < 0) { printf("Factorial of a negative number is not defined.\n"); } else { // Calculate the number of factorial for (int i = 1; i <= num; i++) { product = product * i; // Output result printf("The factorial of %d is :%d\n", i, product); } } return 0; }
Explanation:
- First of all, the user enters a number.
- If the number is negative, the program displays an error message, since factorials are only defined for positive integers.
- If the number is positive, a for loop calculates the factorial by multiplying numbers from 1 to num.
Output:
Enter a number: 5 The factorial of 1 is :1 The factorial of 2 is :2 The factorial of 3 is :6 The factorial of 4 is :24 The factorial of 5 is :120