Lesson goal: Guess a number

Previous: Mouse clicks | Home | Next: I'll guess your number

One of the classic (and early) games to write on a computer is a "guess my number game." The computer chooses a random number from 1 to 100, and your job is to try and guess the number in as few tries as possible.

Continuing your learning of how while loops work, notice we again define a variable called done, which initially starts out as false. The number to guess is also selected and stored in a variable called n. Input is read from the keyboard (which is the player's guess) into variable g. Notice the if g == n statement. If this is true, its body sets done = true, which will terminate the while-loop.

Now you try. Play the game a few times and see if you can understand how it works.

Type your code here:


See your results here: