Designing While Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1
Validation Loops Prompt user for value while value invalid Basic structure: prompt for initial value of variable while condition which is true if not valid explain error and prompt again code using that variable
Validation in Tax Program Use loops to insure income, dependents non-negative – Note no longer separate branch for valid inputs
Sentinel Loops Goal: Continue some action until user wants to quit Example: Converting Fahrenheit to Celsius until user wants to quit
Sentinel Loops Sentinel = variable that stores “quit”/”continue” value Basic structure: set initial sentinel value to “continue” while sentinel != “continue” value do things inside loop prompt user whether to do loop again set sentinel to “quit” if they don’t
Sentinel Example Sentinel: “yes” or “no” value entered by user Prompt at end of loop: “Do you want to convert another temperature (yes or no)?” – Always tell user what the expected values are! Condition: while sentinel == “yes” Initialization: set sentinel to “yes” before loop – Assumption: user will want to convert at least one temperature
Sentinel Example
Menu Example Often use sentinels in menu driven loops – User repeatedly chooses option from menu – One option is quit – Idea: Use menu choice as sentinel Algorithm: initialize choice to something besides “quit” while choice != quit prompt for choice if/elif’s for non-quit choices else error message if not quit
Menu Example
Counting Inside Loop May need to keep track of how many times loop runs – Example: number of guesses in guessing game Use counter variable to keep track of times – Increment variable each time through loop counter_variable += 1 – Initialize before start of loop – Use counter variable inside/after loop as needed
Guessing Game Example Use counter variable to keep track of times – Call it guesses Increment variable each time through loop – guesses += 1 Initialize before start of loop – Set to 1 since that will be the number of guesses if the user enters the correct number the first time Use counter variable inside/after loop as needed – Print the number of guesses after the loop
Guessing Game Example
Loops for Searching Example: Finding which two integers a square root is between Algorithm: – Prompt user for number and keep squaring increasingly higher integers until find one greater than that number Example: number = 11 – 1 2 < 11 – 2 2 < 11 – 3 2 < 11 – 4 2 >= 17 – “Square root of 11 is between 3 and 4
Search Loop Example
Search Loop Ideas Decide what you are searching for, and how you will know you have found it Use a loop to successively narrow the range where the value can be found Example: How would you guess a number between 1 and 100? – Where would the search start? – How would information that guess too high/too low change the range of the search?