Program to find factorials

I have this program working BUT I want to add the ability to keep asking the user to input numbers until they input a correct number. For example, if they input -1, it shows the error, then it asks for another number, if the user inputs another wrong number, it ends the program. However, I want it to keep asking until the user enters a correct number, regardless of how many incorrect numbers the user inputs.

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
36
37
38
39
40
41
#include <iostream>
#include <string>
using namespace std;

int main() {

	int n = 0;
	long long factorial = 1;
	cout << "PLease enter a number between 1-10: " << "\n";
	cin >> n;

	if (n <= 10 && n >= 0) {
		for (int i = 0; i <= n; i++) {
			if (i == 0)
				factorial = 1;
			else
			factorial = factorial * i;
		}
		cout << "Your factorial is: " << factorial << endl;
	}
	else
	{
		cout << "Invalid Number\n" ;
		cout << "Error, enter a number between 1-10: " << "\n";
		cin >> n;
		

		if (n <= 10 && n >= 0) {
			for (int i = 0; i <= n; i++) {
				if (i == 0)
					factorial = 1;
				else
				factorial = factorial * i;
			}
			cout << "Your factorial is: " << factorial << endl;
		}
		return 0;
	}
}




I'm sure this is a simple fix, but I cant figure out what to do. Any hints or advice would be greatly appreciated. Thank you for reading.
Last edited on
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
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>
using namespace std;

int main() {

	int n = 0;
	long long factorial = 1;

cout << "PLease enter a number between 1-10: " << "\n";
	cin >> n;
while ( n != -1)
{
	

	if (n <= 10 && n >= 0) {
		for (int i = 0; i <= n; i++) {
			if (i == 0)
				factorial = 1;
			else
			factorial = factorial * i;
		}
		cout << "Your factorial is: " << factorial << endl;
	}
	else
	{
		cout << "Invalid Number\n" ;
		cout << "Error, enter a number between 1-10: " << "\n";
		cin >> n;
		

		if (n <= 10 && n >= 0) {
			for (int i = 0; i <= n; i++) {
				if (i == 0)
					factorial = 1;
				else
				factorial = factorial * i;
			}
			cout << "Your factorial is: " << factorial << endl;
		}
	}
cout << "PLease enter a number between 1-10: " << "\n";
	cin >> n;
}
return 0;
}


Tell me, what happens if the user enters an invalid number twice? You can use a while loop to make it loop until they enter a valid number, rather than copying out code over and over. Definitely time to read this: http://www.cplusplus.com/doc/tutorial/control/
Topic archived. No new replies allowed.