Factorial Problem

Good evening,

I need help with a problem for my class. I have looked through the forums, and I did not find an answer for my problem. Most of the answers included code that I have not learned yet.

My problem is:

"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." Below is my code, I feel that I am really close, but I just can't get the correct response for the factorial. If anyone could help, I would appreciate it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

#include <iostream>
using namespace std;

int main() {
   int totalVal = 0; 
   int userInt = 0; 
   int i = 0;
   int userSum = 0;
   
   cout << "Please enter an integer." << endl;
   cin >> userInt;
   
   totalVal = userInt;
   for (i = userInt; i >= 1; --i) {
       cout << i << endl;
   }
   
   cout << userInt <<"! is " << totalVal << endl;

   return 0; 
}

 

You set totalVal on line 14 and show it on line 19. Shouldn't the loop do something for the totalVal?

On line 9 you have unused variable userSum. This program does not need such variable. However, it makes me guess that you have had an earlier problem, where you did compute a sum with a loop. Is that true? If it is, then what is the difference between addition and multiplication?


Extra note on "being close". Programming requires paying attention to details.
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.