Processing math: 100%

Lesson goal: The while-loop to guesss your number

Previous: You guess my number | Home | Next: Solving equations

As mentioned, while-loops can make a chunk of program code run over and over until the condition of the while-loop becomes false.

Here's an example of using a while loop: you think of a random number between 1 and 100. The computer will keep guessing WHILE it hasn't guessed your number correctly. Get the use of the "while?"

So go ahead, think of a number between 1 and 100. If you answer the questions truthfully, the computer will guess your number in 10 tries or less every time.

Now you try. Put a condition in the while ... do line to have the loop keep running as long as variable ans "y".

Type your code here:

21
 
1
low=1
2
high=100
3
try = 1
4
ans = ""
5
while ans ~= "y" do
6
 g=math.floor((low+high)/2)
7
 print("try",try,":is your number",g)
8
 print("y=yes, l=too low, h=too high")
9
 ans=input()
10
 if ans == "l" then
11
   low = g 
12
 end
13
 if ans == "h" then
14
   high = g
15
 end
16
try = try + 1
17
end
18
19
if try-1 <= 10 then
20
 print("See! I did it in under 10 tries!")
21
end

See your results here: