Factorial Code

I have to write a code that will calculate the factorial of an entered number and when the number is negative the program will exit the loop and display the message "Goodbye". I am having trouble getting the program to display the message and then properly exit the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 #include <iostream>
using namespace std;

int main ()
{
	unsigned int n = 1;
	unsigned long long factorial = 1;
	int i = 0;

while (n>=0)
{
	cout << "Enter a positive integer (enter a negative number to quit) : ";
	cin >> n;

	if (n>0)
	{
		for (i=1; i <= n ; ++i)
		{
		factorial = factorial*i;
		}
		cout << "The factorial of " << n << " = " << factorial << endl;
		factorial = 1;
	}

	else
	{
		cout << "The factorial of 0 is 1." << endl;
	}

}

cout << "Goodbye!";

	return 0;
} Put the code you need help with here.


Thanks for the help
unsigned int n = 1;
while (n>=0)
{


That's not going to work too good :)
either stop if they enter zero (for example) or remove unsigned keyword.
Last edited on
If n is negative on line 15, the else will be triggered since n is not greater than 0. The simplest fix would be to make line 25 else if (n == 0).
currently n can't be neg, and he can't exit the loop because of it. If he makes the unsigned change, he will also need this logic ... good catch on that.


Topic archived. No new replies allowed.