Factorial Calculation Program in C++
This program calculates the factorial of a given number using C++. 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! and is defined as:
n! = n * (n - 1) * (n - 2) * ... * 1
For example:
- 5! = 5 * 4 * 3 * 2 * 1 = 120
- 4! = 4 * 3 * 2 * 1 = 24
- 3! = 3 * 2 * 1 = 6
Program Code
#include <iostream>
// Function to calculate factorial
unsigned long long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int number;
std::cout << "Enter a number to calculate its factorial: ";
std::cin >> number;
if (number < 0) {
std::cout << "Factorial is not defined for negative numbers." << std::endl;
} else {
unsigned long long result = factorial(number);
std::cout << "The factorial of " << number << " is " << result << "." << std::endl;
}
return 0;
}
Explanation
Here is a detailed explanation of the program:
1. Include the iostream Library
#include <iostream>
This line includes the iostream library, which is used for input and output operations.
2. Factorial Function
unsigned long long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
This function calculates the factorial of a given number recursively. If the number is 0 or 1, it returns 1 (base case). Otherwise, it calls itself with n-1 and multiplies the result with n (recursive case).
3. Main Function
int main() {
int number;
std::cout << "Enter a number to calculate its factorial: ";
std::cin >> number;
if (number < 0) {
std::cout << "Factorial is not defined for negative numbers." << std::endl;
} else {
unsigned long long result = factorial(number);
std::cout << "The factorial of " << number << " is " << result << "." << std::endl;
}
return 0;
}
The main function does the following:
- Prompts the user to enter a number.
- Reads the input number.
- Checks if the number is negative. If so, it prints a message stating that factorial is not defined for negative numbers.
- If the number is non-negative, it calls the factorial function and stores the result.
- Prints the factorial of the entered number.