Modify the given code such that negative inputs do not break the program and the
ID: 3541888 • Letter: M
Question
Modify the given code such that negative inputs do not break the program and the smallest number that broke the program before now works. Do not hardcode answers.
#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(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);
}
int factorial(short number)
{
if(number<0)
{
return -1;
}
int accumulator = 1;
while (number > 0) {
accumulator = accumulator * number;
number = number-1;
}
return accumulator;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.