I'm going through the practice problems listed on the site because I am sort of self teaching myself c++ and I need some help with one of the problems.
This is the problem: 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
#include <iostream>
usingnamespace std;
int main()
{
int num;
cout << "Please enter a number other than 5: ";
cin >> num;
if (num != 5)
{
for (int i = 0; i < 9; i++)
{
cout << "Try again: ";
cin >> num;
if (num == 5)
{
return 0;
}
}
cout << "You are more patient then me. You win. " << endl;
}
elseif (num ==5)
{
cout << "Hey! you weren't supposed to enter 5!";
}
return 0;
}
I'm not sure if I should have a "return 0" within a for loop. Not sure if that is the proper format. Also if there is a better way to write the code i.e. use a do,while or some other way, I would appreciate a different perspective.
Also if anyone could give a little head start to this problem.
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.)
Thanks for the reply. I certainly see how a program can get written differently by anyone, but I also think that there is a general efficient way to write certain codes.
Would you be able to tell me how I could write a loop program without having to rely on the "result 0"?
I managed to figure out the last part of the question with your help, but I still end up with have to use a "result 0" or it will loop forever.
I've taken an introductory c++ course before and was told that "break;" shouldn't be used in code unless there was a switch statement? Is that true? Does the same rule apply to result 0?
I want to make sure I start off on the right foot.
#include <iostream>
usingnamespace std;
int main (void)
{
int a = 0;
int choice=0;
while(1)
{
cout << "Please enter a number other than " << a << ": ";
cin >> choice;
if (choice == a)
{
cout << "You were not supposed to enter " << a << "!" << endl;
return 0;
}
a++;
}
return 0;
}
#include <iostream>
usingnamespace std;
int main (void)
{
int a = -1;
int choice=0;
do
{
a++;
cout << "Please enter a number other than " << a << ": ";
cin >> choice;
}while(choice != a);
cout << "You were not supposed to enter " << a << "!" << endl;
return 0;
}