I'm suppose to write a code that ask the user to guess until the user picks the number 4. Once the user picks, the number the code keeps looping with the statement and won't ask the user again for a number. How do I get it to prompt the user again if they don't pick the number 4?
You dont want to be using a while loop, but rather a do-while loop. Hopefully this code will help you understand -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int userGuess = 0;
int answer = 4;
cout << "Guess a number between 1 and 10: ";
do
{
cin >> userGuess;
if (userGuess < 1 || userGuess > 10)
cout << "You are not following instuctions!" << endl;
elseif (userGuess != answer)
cout << "wrong awnser! try again!" << endl;
}
while (userGuess != answer);
cout << "You gessed correctly!" << endl;
The reason as to why you want to use a do-while loop and not a while loop is because, You want the user to guess FIRST and then check if it is right or not.
Also, it is not supposed to look like ((userGuess <=1 || userGuess >= 10)) like @bdanielz suggested, but rather like this (userGuess < 1 || userGuess > 10)
Both the number 1 and 10 is between 1 and 10 (I sure hope so).