I have written the program that ccontinues to ask the user to enter any number other than 5 until the user enters the number 5. However, I have a question where I am doing it wrong as after 10 iterations if the user still hasn't entered 5, the program will tell the user "Wow, you're more patient then I am, you win." and exit?
My code is here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main() {
int number;
for (int i = 0; i < 10; i++) {
if (i==9) {cout << "Wow, you're more patient than I am, you win." << endl; return 1;}
do {
cout << "Enter number" << endl;
cin >> number;
} while(!(number == 5)); { cout << "Hey! You weren't supposed to enter 5!" << endl;}
}
return 0;
}
#include <iostream>
int main() {
int number;
int count = 1;
do {
std::cout << "Attempt no. " << count << " Enter number: ";
std::cin >> number;
if (number != 5)
std::cout << "Hey! You were supposed to enter 5!\n";
count++;
} while(number != 5 && count <= 3);
std::cout << "I give up\n";
return 0;
}
The other part of the assignment is this: 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.).
I have this program, but when it is asked to enter any number other than 0, 1, 2, 3, etc I get the error message if I enter 0, 1, 2 or 3 for any of the cases. Why is that because my logic seems valid? Thank you!
the code is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int main() {
int number, count = 0, i;
for (i=0; i<=10; i++) {
while(number != i && count <= 10) { cout << "You weren't supposed to enter that!" << endl; return 1;}
cout << "Please enter any number other than " << i << ":" << endl;
cin >> number;
count++;
}
return 0;
}
One thing I'd suggest is just have one statement per line. There are a lot of people who think it makes their code look more professional but it is the exact opposite. :)
while(number != i && count <= 10) { cout << "You weren't supposed to enter that!" << endl; return 1;}
This is not good as all one line, but it's up to you.
1 2 3 4 5
while(number != i && count <= 10)
{
cout << "You weren't supposed to enter that!" << endl;
return 1;
}
Proper formatting with whitespace, as kemort showed, makes it easier to debug when problems happen. When you cram multiple statements on one line figuring out what statement is flawed is MUCH harder.
Other people reading your code will have a hard time trying to figure out what you trying to do. Most people will just give up.