C/C++ How do I compute N factorial in C++?

  • Thread starter Thread starter carl123
  • Start date Start date
  • Tags Tags
    C++ Program
Click For Summary
The discussion revolves around creating a program that calculates the factorial of a user-input integer N. The initial code provided has placeholders for user input and a loop to compute the factorial. Key points include initializing a variable `totalVal` to store the factorial result and using a while loop to multiply values from N down to 1. A suggestion is made to limit the input to integers between 1 and 12 due to potential overflow issues with larger factorials. The program's complexity increases significantly for values beyond 20!. The final implementation includes user prompts and a loop that efficiently computes the factorial, while also noting that multiplying by 1 is unnecessary.
carl123
Messages
55
Reaction score
0
Write a program that let's 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.

#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;
}
 
Technology news on Phys.org
#include <iostream>
using namespace std;

// If no checks for invalid input

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

// FIXME: Ask user to input an integer, store in userInt
cout << ("Enter integer value > 0") <<endl;
cin >> userInt;

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

int temp = userInt;
while(temp>1)
{
totalVal*= --temp;

}

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

return 0;
}
 
The while loop can be
while(temp > 2);
No point in multiplying by 1.

The program only works up to 12! Probably should be a bounds check for an integer from 1 to 12.
It gets a lot more complicated if you want it to go beyond 20!
 
I just completed the program. Did not write new :)
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
2K
Replies
1
Views
8K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 15 ·
Replies
15
Views
4K
Replies
12
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
Replies
12
Views
2K
  • · Replies 40 ·
2
Replies
40
Views
3K
  • · Replies 6 ·
Replies
6
Views
12K
  • · Replies 39 ·
2
Replies
39
Views
4K