Hey everyone,
I'm working out some of the practice problems that are on this website, and I just had a question about this one.
"Write a program that ccontinues to asks the user to enter any number other than 5 until the user enters the number 5.
Then tell the user "Hey! you weren't supposed to enter 5!" and exit the program.
★ Modify the program so that after 10 iterations if the user still hasn't entered 5 will tell the user "Wow, you're more patient then I am, you win." and exit.
★★ Modify the program so that it asks the user to enter any number other than the number equal to the number of times they've been asked to enter a number. (i.e on the first iteration "Please enter any number other than 0" and on the second iteration "Please enter any number other than 1"m etc. etc. The program must behave accordingly exiting when the user enters the number they were asked not to.)"
Now I've almost figured out everything (though it may not be the best way to do everything) except for 2 star portion of the question. I used a switch statement to determine if the input is valid, and I'm not sure how to make a 'case' that allows me to refer to whatever number 'i' is. Obviously 'i' changes depending on how many times the loop has been run through, so it the case number has to change every time. Is there a way to do this?
And also, even though the problem didn't ask for it, I wanted to make it where if an invalid character (such as a letter, or '@') was entered, the program would end. What's the best way to do this?
I know this is pretty basic stuff, but I've been teaching myself and between school and a job, it's tough to learn as quickly as I'd like.
Thank you for any feed back!
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
|
// Picking Numbers
#include <iostream>
using std::cout;
using std::cin;
int main()
{
int number = 0; // Integer entered by user
int i = 0; // Loop counter
for (i = 0; i < 10; ++i) // Loop that stops program when a number has succesfully been entered 10 times
{
cout << "Please enter any number other than a " << i << " or a 5.\n\n";
cin >> number; // User input
switch (number) // Switch statement to determine if what the user entered is valid
{
case 5: cout << "You weren't supposed to enter a 5.";
return 0; // Ends program
case i: cout << "You weren't supposed to enter a " << i << " !";
return 0; // Ends program
default: break; // Any number other than a 5 or 'i' entered causes the program to loop back until 10 valid numbers have been entered
}
}
cout << "Good job you entered a valid number 10 times in a row!";
}
|