# While Loops. Challenge: ● Ask the user a simple math questions ● Continue asking the question until the user gets it right.

## Presentation on theme: "While Loops. Challenge: ● Ask the user a simple math questions ● Continue asking the question until the user gets it right."— Presentation transcript:

While Loops

Challenge: ● Ask the user a simple math questions ● Continue asking the question until the user gets it right

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

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

A while loop officially requires: ● only A condition

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

Bad Loop new program badLoop new variable lap = 0 while lap <= 10 laps++ end while end program

Another Bad Loop new program badLoop new variable lap while lap != 10 lap = lap + 3 end while end program

Yet another bad Loop new program badLoop new variable lap = 0 while lap <= 0 lap++ end while end program

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

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

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

Download ppt "While Loops. Challenge: ● Ask the user a simple math questions ● Continue asking the question until the user gets it right."

Similar presentations