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.
#include <iostream>
#include <string>
usingnamespace std;
int main() {
int n = 0;
longlong 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/