Jordan Molina
Jordan Molina

Reputation: 27

Inner while loop iteration with outer loop

I have a simple nested while loop situation but I'm not sure how to increment numGuesses inside the second loop to escape the first loop once it is no longer less than 5.

while(numGuesses<5){
    while(!correct){
        cout << "\nGuess the number the computer randomply picked between 1 - 100: ";
        numGuesses++;
        cin >> guess;
        if(guess<number){
            cin.clear(); //clears input stream
            cin.ignore(256, '\n');
            cout << "\nSorry, your guess is too low";
        }
        else if (guess>number){
            cout << "\nSorry, your guess is too high";
        }
        else{
            cout << "\nYou guessed right, you win!";
            correct = !correct;
        }
    }
    
}
cout << "Sorry, you lost. The number is: " << number;

Each time the inner while loop iterates I would like numGuesses to increase but I'm guessing its not in its scope?

Upvotes: 0

Views: 205

Answers (2)

Anonymous1847
Anonymous1847

Reputation: 2598

You should just use one while loop! After all, the thing you're looping over is prompting for a guess. There's no need for a second layer of looping inside that. Think about when you want to stop asking for a guess -- when the guesses get to 5 or when they get it correct. So when do you want to keep asking for a guess? When the guesses are less than 5 and they have not got it correct. Also, you want to say whether they lost after the end of the loop depending on the value of correct.

while(numGuesses<5 && !correct) {
    cout << "\nGuess the number the computer randomply picked between 1 - 100: ";
    numGuesses++;
    cin >> guess;
    if(guess<number){
        cin.clear(); //clears input stream
        cin.ignore(256, '\n');
        cout << "\nSorry, your guess is too low";
    }
    else if (guess>number){
        cout << "\nSorry, your guess is too high";
    }
    else{
        cout << "\nYou guessed right, you win!";
        correct = !correct;
    }
}
if (!correct) { // loop stopped before they got it correct
    cout << "Sorry, you lost. The number is: " << number;
}

You'll also want "\n"s or std::endls at the end of your print statements, otherwise your code will print everything on one line.

Upvotes: 3

vmp
vmp

Reputation: 2420

You don't need 2 whiles...

while(numGuesses < 5 && !correct)
{
       // your logic here
}

After that you can check either the variable correct or numGuesses. For example:

if(!correct)
    // your code

Upvotes: 1

Related Questions