Factorial calculation
Write a C++ program that calculates the factorial of a given number.
Before calculating the factorial, use a do-while loop to make sure that the user inputs a non-negative integer.
Then, use a for loop to calculate the factorial of the given number.
Answer
#include <iostream>
int main() {
// Get input from user until it is non-negative
int input;
do {
std::cout << "Enter a non-negative integer: ";
std::cin >> input;
} while (input < 0);
// Calculate factorial by multiplying all numbers from 1 to input together
int factorial = 1;
for (int i = 1; i <= input; ++i) {
factorial *= i;
}
// Print result
std::cout << "Factorial of " << input << " = " << factorial << "\n";
}
Integers aren't large enough
ints only take up 4 bytes of memory.
Because of this the highest value they can store is 2,147,483,647.
The factorial of 13 is 6,227,020,800.
Because of this we need to use a larger datatype to store the factorial.
unsigned long long factorial = 1;
Depending on compiler and system architecture; a long is either 4 or 8 bytes. The long long type ensures at least 8 bytes, offering a larger range of values than a single long.
The unsigned keyword specifies that a variable can only hold positive numbers (or 0).
This effectively doubles the positive range.
For refference:
unsigned long long has a range from 0 to 18,446,744,073,709,551,615.
long long has a range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.