1 / 12

While Loops

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

cstrock
Télécharger la présentation

While Loops

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 actuallyrequires: • 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 actuallyrequires: • 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

More Related