Write a C++ program that computes the factorial of a given non-negative integer N provided by the user.
Input and Output Examples
- Input: 5
Output: The factorial of 5 is 120. - Input: 7
Output: The factorial of 7 is 5040.
Algorithm to calculate the factorial of a number:
- Start the Program: Include necessary headers and declare the use of the standard namespace.
- Prompt for Input: Request the user to enter a non-negative integer n.
- Read the Input: Store the input in a variable n.
- Calculate the Factorial: Use a method (iterative or recursive) to calculate the factorial of n.
- Display the Output: Output the factorial of n.
- End the Program: Finish execution cleanly.
Method 1: Iterative Approach
This method uses a loop to calculate the factorial by iteratively multiplying the numbers.
cpp
#include <iostream>
using namespace std;
int main() {
unsigned int n; // Declare an unsigned integer for the input to ensure non-negative numbers.
unsigned long long factorial = 1; // Use a long long type to handle larger results.
cout << "Enter a non-negative integer: ";
cin >> n;
// Calculate factorial iteratively
for (int i = 1; i <= n; ++i) {
factorial *= i; // Multiply factorial by each number up to n.
}
cout << "The factorial of " << n << " is " << factorial << "." << endl; // Display the result.
return 0; // End the program successfully.
}
Method 2: Recursive Approach
Using recursion, the factorial function calls itself until it reaches the base case.
cpp
#include <iostream>
using namespace std;
// Function to calculate factorial recursively
unsigned long long factorial(unsigned int n) {
if (n == 0) return 1; // Base case: the factorial of 0 is 1.
return n * factorial(n - 1); // Recursive case: n times factorial of (n-1).
}
int main() {
unsigned int n; // Declare an unsigned integer to ensure the input is non-negative.
cout << "Enter a non-negative integer: ";
cin >> n;
// Call the recursive factorial function
unsigned long long result = factorial(n); // Compute factorial using recursion.
cout << "The factorial of " << n << " is " << result << "." << endl; // Display the result.
return 0;
}