The Guessing Game

Controlling Iteration

We still have not done anything about stopping the iteration. I was putting that off until after you got the end points moving properly, because the iteration is done when the two points meet. Well, loosely. When the calculated middle is equal to either the top or the bottom, then it is the number they chose.

Now you are there. Depending on their answers, the top or bottom keep coming in towards the actual number the other person chose (you already did that, right?) and pretty soon they meet. Well probably not. If you try your program on the Kitchen computer now (use the button below) you will see that pretty soon it is asking its question with fractional (has a decimal point) middles. That's easily fixed by rounding the value to the nearest whole number before using it:

round middle
Now when top = bottom+1, then bottom will be the chosen number. Except if you are trying to guess 99, in which case it will fail. This is called an "edge case" and programs often fail because we did not consider the edge cases. There's a simple solution to this one: you tell the other person "to 99" but you tell the computer "to 100." That way, when it can't find the top number in its range, no harm, because the person doesn't know to choose 100. Other edge cases are a lot harder to fix.

Don't forget to print out your guess, after your iteration terminates.

Are you ready to try your program again?

If it doesn't work -- probably: almost never does a program work properly the first (or second or third...) time you try it -- and if you cannot see what you might have told the computer to do that isn't what you wanted, you can turn the page, and then compare your program line by line, to mine to see what you did differently.

If your program works great, you might look at mine anyway, or just save your program text in a separate file, then move on to your second game, Rock-Paper-Scissors (just text input and output).

Five Basic Concepts
Sequence
Iteration
Conditional
Variables
Input/Output

 

<<Previous | ToC | Next >>

[2021 June 3]