I am supposed to compute a factorial where The program asks the user for input, and stores it in userInt, A loop is set up to compute the factorial, The loop starts with the loop variable at (userInt – 1). The totalVal is multiplied by the loop variable with each iteration. The loop variable is decremented with each iteration. The program produces and displays correct results.
I am doing this totally wrong, and no one seems to be able to help.
#include <iostream>
usingnamespace std;
int main() {
int totalVal = 0;
int userInt = 0;
// FIXME: ask user to input an interger and assign it to userInt.
cout << "Enter an interger.";
cin >> userInt;
totalVal = userInt;
while (totalVal >= 1) {
userInt = (userInt -1);
userInt = userInt * totalVal;
}// FIXME: Add while loop that counts down to 1, updating totalVal
cout << userInt <<"! is " << totalVal << endl;
return 0;
} Put the code you need help with here.
Line 14 should be while (userInt >= 1) {
Line 16 should be totalVal = userInt * totalVal;
Of course, what you should really do is have a third integer variable to use for the loop instead of changing userInt. Right now, line 19 will not display what you want.
It can be a for loop or a while loop. I am doing a bad job of explaining the problem. There is an additional instruction with it:
Write a program that lets a user enter N and that outputs N! (meaning N*(N-1)*(N-2)*...*2*1). Hint: Initialize a variable totalValue to N, and use a loop variable i that counts from N-1 down to 1.