290 likes | 504 Views
The while loop. General Structure Ex1 : validating 1 input Ex2 : validating multiple inputs Ex3: Running total Infinite while loops. 1. Definition/Flowchart. A while loop repeats a block of code while a condition is true . In other words :
E N D
The while loop General Structure Ex1 : validating 1 input Ex2 : validating multiple inputs Ex3: Running total Infinite while loops
1. Definition/Flowchart • A while loop repeats a block of code while a condition is true. • In other words: A while loop repeats the loop body until a condition becomes false. BE CAREFUL! The condition is ALWAYS written as “THE TEST TO CONTINUE” (not “the test to quit”)
2. General Structure • Main structure: Initialization whilecondition Code you wish to repeat Update of condition Note: In the block of code, the variables involved in the condition MUST be updated to avoid an infinite loop. end Loop Body
Examples • A common use of a while loop is to ‘trap the user’ until s/he gives a valid input • Examples: • Prompt for a radius until positive (a radius must be positive or zero) • Prompt for the number of die to roll (this value has to be strictly positive!) • Prompt for the volume of fuel to be processed into the vehicle (there is always an upper limit value) • …
Ex1: Validating one input • Checking for a particular input that must be between 0-100 (included) %Initialize first reading reading = input(‘Enter reading (between 0-100): ’); % Repeat as long as there is an error %Ask for reading again to update value
Ex1: Validating one input • Checking for a particular input that must be between 0-100 (included) %Initialize first reading reading = input(‘Enter reading (between 0-100): ’); % Repeat as long as there is an error %Ask for reading again to update value reading = input('Re-enter reading. MUST be from 0-100: ');
Ex1: Validating oneinput (NEVER two at the same time!) • Checking for a particular input that must be between 0-100 (included) %Initialize first reading reading = input(‘Enter reading (between 0-100): ’); % Repeat as long as there is an error while ______________________________________ %Ask for reading again to update value reading = input('Re-enter reading. MUST be from 0-100: '); end
Ex2: Numerous inputs • Prompt the user for a width, height, and depth in inches. Compute the volume. Prompt again when invalid inputs.
Ex2, algorithm • Prompt the user for a width, height, and depth in inches. Compute the volume. Prompt user when invalid inputs. % prompt for width until valid % prompt for height until valid % prompt for depth until valid % calculate/display volume of tank
Ex2, code % prompt for width until valid width = input(‘Enter a positive width (inches): ’); while ___________ width = input(‘ERROR: width strictly positive only --> ’); end % prompt for height until valid % prompt for depth until valid % calculate volume of tank
Ex2, code % prompt for width until valid width = input(‘Enter a positive width (inches): ’); while width<=0 width = input(‘ERROR: width strictly positive only --> ’); end % prompt for height until valid height = input(‘\nEnter a positive height (inches): ’); whileheight <=0 height = input(‘ERROR: height strictly positive only --> ’); end % prompt for depth until valid % calculate volume of tank
Ex2, code % prompt for width until valid width = input(‘Enter a positive width (inches): ’); while width<=0 width = input(‘ERROR: width strictly positive only --> ’); end % prompt for height until valid height = input(‘\nEnter a positive height (inches): ’); whileheight <=0 height = input(‘ERROR: height strictly positive only --> ’); end % prompt for depth until valid depth = input(‘\nEnter a positive depth (inches): ’); whiledepth <=0 depth = input(‘ERROR: depth strictly positive only --> ’); end % calculate volume of tank volumeTankIn3 = width*height*depth;
Ex2, code % prompt for dimensions width = input(‘Enter a positive width (inches): ’); height = input(‘Enter a positive height (inches): ’); depth = input(‘Enter a positive depth (inches): ’); % while at least one invalid, ask again whilewidth<=0 || height <=0 || depth <=0 height = input(‘ERROR: height strictly positive only --> ’); depth = input(‘ERROR: depth strictly positive only --> ’); width = input(‘ERROR: width strictly positive only --> ’); end % calculate volume of tank volumeTankIn3 = width*height*depth; BAD!!!!! Do ONE input at a time!
Ex3: Running Totals • Ask user for a list of scores. Add all scores together. Stop asking when a negative/or null score is entered! The number of times the loop will repeat a block of code is not known. It will be determined as the code runs.
Ex3: Running Totals • This code involves having a“RUNNING TOTAL”. • “As the code RUNS, the TOTALis repeatedly updated”. • Note: each individual value (6,13,27) are not of any interest once the TOTAL is calculated. 6 points 13 points 27 points Scoring Sheet. http://the.mcwessels.org/2009/09/
Ex3, algorithm • Ask user for a list of scores. Add all scores together. Stop asking when a negative/or null score is entered! % start score total at zero % prompt for first score (and give directions) % As long as score is positive % “running total”: add score to total, as each given % ask for next score % display total score to the screen
Ex3, code % prompt for a score(and give directions) fprintf(‘Note: a negative/zero score quits.\n’); score = input(‘Enter first score: ’); totalScore = 0; %start total score at zero % while score is positive while score>0 % “running total”: add score to total as each given totalScore= totalScore + score; % ask for next surface value score = input(‘Next score: ’); end % display total score to the screen fprintf(‘All the scores add up to %.2f!\n’, totalScore);
An INFINITE loop… Oops…
Example: Infinite Loop • A loop is said to be infinite when, the body of the loop never stops repeating. It is caused by a loop condition that (once started) never becomes false. • This is usually due to: • A bad initialization • A typo in the condition (wrong operators) • A code block that does not change the condition • Examples x = 10; while x>0 x = x + 1; end x = input(‘Enter x: ’); while x<0 input(‘ERROR: enter x again: ’); end
Example: Infinite Loop • Omitting semi-colons is a great way to know why a loop is infinite. >> >> x = 10 x = 11 x = 12 x = 13 x = 10 while x>0 x = x + 1 end BAD
Example: Infinite Loop BAD x = input(‘Enter x: ’) while x<0 input(‘ERROR: enter x again: ’) end >> >> Enter x: -5 x = -5 ERROR: enter x again: 5 ans = 5 ERROR: enter x again:
Infinite loop • Infinite Loop Once begun, the loop condition never becomes false • Use CTRL+C in the command window to break it • Except when the loop opens dialog boxes… then you will use alt-F4
Key Ideas • A while loop repeats a block of code while a condition is true. • Structure: Initialization, while condition, code to be repeated, update of condition, end • Common Uses: • trap the useruntil a valid input is given (relational operators, boolean operators, even, odd, integers, etc.) • running total until a condition is met • Infinite loop occurs when the loop condition is never updated to a false condition while in the loop • To stop an infinite loop: Ctrl-C