Download presentation
Presentation is loading. Please wait.
Published byLondon Tayler Modified over 9 years ago
1
While Loops
2
Challenge: ● Ask the user a simple math questions ● Continue asking the question until the user gets it right
3
A while loop actually requires: ● A sentry variable ● An initial value for the sentry ● A condition that can be triggered to end the loop ● A statement inside the loop that somehow changes the sentry
4
Math Algorithm New program math game new integer correct = 5 new integer guess = 0 while (guess != correct) guess = input(“what’s 2 + 3?”) if (guess == correct){ output (“great!”) else output (“try again...”) end if end while end program
5
A while loop officially requires: ● only A condition
6
A while loop actually requires: ● A sentry variable ● An initial value for the sentry ● A condition that can be triggered to end the loop ● A statement inside the loop that somehow changes the sentry
7
Bad Loop new program badLoop new variable lap = 0 while lap <= 10 laps++ end while end program
8
Another Bad Loop new program badLoop new variable lap while lap != 10 lap = lap + 3 end while end program
9
Yet another bad Loop new program badLoop new variable lap = 0 while lap <= 0 lap++ end while end program
10
Challenge ● Change the math program so it gives no more than three chances ● Hint: still uses a while loop ● Hint: count number of turns ● Hint: add a special kind of sentry
11
Three Tries Algorithm New program three tries new integer correct = 5 new integer guess = 0 new integer turns = 0 new boolean keepGoing = true while (keepGoing == true) guess = input(“what’s 2 + 3?”) if (guess == correct) output (“great!”) keepGoing = false else output (“try again...”) end if turns++ if (turns >= 3){ output “too many turns” keepGoing = false end if end while end program
12
Tricks of the Three Tries Use a boolean (true/false) sentry keepGoing indicates whether loop should continue Anything that causes loop to end changes keepGoing
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.