The Guessing Game

Variables

Did you ever have a pocket calculator? There's probably a calculator app on your smart phone or maybe on this computer. Most calculators have a "Memory" key for saving or accumulating results so you can use them later in a different calculation, or maybe just to look at it when you finish. But mostly nobody ever uses the Memory key. It's really handy when doing a lot of calculations. In computer programs that "memory" is called a "variable" (the fourth item in the Five Concepts in the list below) and you can have as many of them as you need, you just give a different name to each. The "variable" part of a variable is that you can keep putting different values into them, and they remember the last value you put there.

The first time we ask the question in your iteration, you want the computer to ask "Is your number less than 50?" (halfway between 1 and 99). Then if the other person says "Yes" the second question will pick the middle of the new range, 1 to 49, so you ask "Is your number less than 25?" If they said "no" then the range we are considering is 50 to 99, and the middle of that is 75.

Do you know how to find the middle between two numbers? There are several ways. You could count forward from the lower number and simultaneously count back from the other, and when your two counts meet, that is the middle. Or you can take the difference (subtract) the two numbers, cut that in half, then add it to the smaller number. I think the fastest and simplest way is to add the two numbers together, then take half of the sum. You should try it with a couple examples to convince yourself that all three methods give the same answer. Math is like that: if you don't make a mistake, every different way to do it gives the same answer. So pick the easy one.

Let's make a variable for this middle number, call it middle:

Variable middle = 50
Where do you think we should put this line in your Program? Insert it there, then rewrite the question inside the iteration to use this variable, then turn the page.
Five Basic Concepts
Sequence
Iteration
Conditional
Variables
Input/Output

 

<<Previous | ToC | Next >>

[2021 April 19]