Since we know that only a small number of inputs produce valid outputs, we can a
ID: 3541889 • Letter: S
Question
Since we know that only a small number of inputs produce valid outputs, we can alternatively hardcode the factorials of these inputs. Rewrite the program from the previous part using a switch statement to demonstrate for inputs up to 10 how you would do this.
#include <iostream>
#include <cstdlib>
using namespace std;
/*
* Will compute and return the factorial value of the given number.
* Remember factorial is the product of all positive integers less
* than or equal to the given number.
*
* e.g 4! = 4 * 3 * 2 * 1 = 24
*/
int factorial(short number);
int main() {
short number;
cout << "Enter a number: ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number) << endl;
exit(EXIT_SUCCESS);
}
/*
* Will compute and return the factorial value of the given number.
* Remember factorial is the product of all positive integers less
* than or equal to the given number.
*
* e.g 4! = 4 * 3 * 2 * 1 = 24
*/
int factorial(short number) {
//start our accumulator at 1 since 0! == 1
int accumulator = 1;
//until we reach 0
while (number > 0) {
//multiple our product by the current number
accumulator = accumulator * number;
//then decrement to the next lowest value
number = number-1;
}
return accumulator;
}
Explanation / Answer
#include <iostream>
#include <cstdlib>
using namespace std;
int factorial(int number);
int main()
{
int number;
cout << "Enter a number: ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number) << endl;
exit(EXIT_SUCCESS);
}
int factorial(int number)
{
switch(number)
{
case 0:
return 1;
case 1:
return 1;
case 2:
return 2;
case 3:
return 6;
case 4:
return 24;
case 5:
return 120;
case 6:
return 720;
case 7:
return 5040;
case 8:
return 40320;
case 9:
return 362880;
case 10:
return 3628800;
}
return -1;
}