Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Let's say I have a game that ends where the user guesses what number was picked by a random number generator. They have a maximum of ten guesses and if they get 4 right the game ends.

If I declare a variable called winCounter and a variable called guessCounter can I make a while loop that continues while winCounter != 4 or guessCounter != 10?

share|improve this question
6  
while winCounter != 4 or guessCounter != 10? That's basically the code right there! – MattDavey Nov 7 '12 at 21:18
3  
learn about the && and || operators. Also you'd want inequalities instead of !=. – whatsisname Nov 7 '12 at 21:20
1  
Not quite that simple, @MattDavey. Consider if winCounter is 4. guessCounter will still not be 10, so the loop will continue until both conditions are met. – Karl Bielefeldt Nov 7 '12 at 21:56

closed as off topic by Robert Harvey, Walter, FrustratedWithFormsDesigner, gnat, ElYusubov Nov 8 '12 at 0:08

Questions on Programmers Stack Exchange are expected to relate to software development within the scope defined in the FAQ. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about closed questions here.

1 Answer

The AND (&&) operator returns true if both of its arguments are true. Otherwise it returns false.

The OR (||) operator returns true if either of its arguments are true, otherwise false.

You want the loop to continue until either of the following conditions occurs:

  • winCounter >= 4 --- if they get 4 (or more) right, the game ends
  • guessCounter >= 10 --- if they guessed ten (or more) times, the game ends

Or, to put it another way, you want the loop to continue looping while both of these conditions remain true:

  • winCounter < 4
  • guessCounter < 10

We'll go with the latter since it's a simpler loop condition.

If either of these conditions is false, you want the loop to stop; you want the loop to continue only while both the conditions are true.

We can use the AND (&&) operator to tell us when either of the conditions stops being true -- because the && will only return true if both of its arguments are true.

So, if we AND together winCounter < 4 and guessCounter < 10 then when either stops being true the && will stop being true and that means we should exit the loop.

while ( (winCounter < 4) && (guessCounter < 10) )
{
    ...
}
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.