The Guessing Game

Calculating with Variables

We have two end points, the top (initially 99) and the bottom (initially 1). So we can make two variables and put them right at the front of the program:

let top = 99
let bottom = 1
later on, inside the loop, after the person has answered the question, we can change the values appropriately.

Now we can calculate -- that is, let the computer calculate, because it's good at that -- what the midpoint is:

let middle = (top+bottom)/2
Why do you think I put those parentheses there? Traditionally, we always do any multiplication or division before we use those results in addition, except we use parentheses in computer programs as shorthand for "first do the addition, then divide the sum by 2." Where do you think this line should go?

After the other person answers your question -- how do you know what they answered? Right, another variable!

input answer
How do they know what to type in as an answer? Because your program will tell them: Those five characters "(y/n)" tells most people that they should type either a "y" or a "n". We also want to tell the computer that we want a single letter input (the 1 does that in Kitchen).
Say "Is your number less than " middle "? (y/n)"
input answer 1

We still need to do something with their answer. If they answered "y" then we need to change the value of variable top to what was the middle (and leave the bottom unchanged). If they answered "n" (or anything else) we need to move bottom up to where middle is and leave top unchanged. Which of our Five Concepts in the list below do you think does what we want here? Can you add that to your program? Then turn the page.

Five Basic Concepts
Sequence
Iteration
Conditional
Variables
Input/Output

 

<<Previous | ToC | Next >>

[2021 April 22]