HELP!

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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 #include <iostream>
using namespace 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.
This is the original code.

#include <iostream>
using namespace std;

int main() {
int totalVal = 0;
int userInt = 0;

// FIXME: Ask user to input an integer, store in userInt

totalVal = userInt;
// FIXME: Add while loop that counts down to 1, updating totalVal

cout << userInt <<"! is " << totalVal << endl;

return 0;
}
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.
Last edited on
I tried that too. No matter what input I enter, it keeps coming back 0! is 0.
I'm used to using for loops instead of while loops, so I made a mistake.

Line 14 should be while (userInt > 1)
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.
Topic archived. No new replies allowed.