FAQ: Loops - Guess Number


Hello guys, I’m new here. I did this exercise and it shows me the error like I didn’t add the while loop.
But when I compile and execute, it works just fine. I had to replace with solution to continue to the next lesson.
Am I wrong or not?

When I try the following code:

#include

int main() {

int guess;

int tries = 0;

std::cout << “I have a number 1-10.\n”;
std::cout << "Please guess it: ";
std::cin >> guess;

// Write a while loop here:
while (guess != 8 && tries < 50) {

std::cout << "Wrong Guess, try again: ";

tries++;

}

if (guess == 8) {

std::cout << "You got it!\n";

}

}

It works for a correct answer put posts out 50 lines of “Wrong Guess, try again.”

Did I make a mistake somewhere?

Have a closer look inside your while loop. Inside that loop, you are printing out a message and then incrementing tries. What’s missing? Shouldn’t you be doing something else as well between these two actions? If you are just doing these two actions, then unsurprisingly you will see the same message printed 50 times.

If you are still stuck, have a closer look at the instructions. You will see the code you are missing mentioned explicitly in the snippet in the instructions.

My code functions fine but I keep getting the error “did you add the while loop?”
It compiles fine, and works as it should:

#include <iostream> int main() { int guess; int tries = 0; std::cout << "I have a number 1-10.\n"; std::cout << "Please guess it: "; std::cin >> guess; // Write a while loop here: while ( guess != 8 && tries < 50){ std::cout<<"Wrong guess, try again: "; std::cin >> guess; tries++; } if (guess == 8) { std::cout << "You got it!\n"; } }