Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.

Similar presentations


Presentation on theme: "Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1."— Presentation transcript:

1 Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1

2 1. General Knowledge Loops are used to repeatedly execute lines of code. There are 2 basic uses for loops 1.Make some code repeat as long as a condition is true Example: Ask for username/password until the user gives a correct combination Example: Allow the user to repeat the entire code, until s/he quits 2.Make some code repeat a certain number of times (next lecture) Example: Ask for exactly 5 grades. Note that the number of repetitions may not be known until run-time: e.g. User input tells the program how many grades to provide. 2

3 General Knowledge, cont. Regardless of which use, four criteria are common to both. When repeating anything, a loop needs: A starting point: “Initialization step” A decision for continuing: “Condition” A means to control the loop: “Loop control variable” An “update” step for the next iteration 3

4 2. Two types of loops MATLAB has two loops, one for each method explained previously: while – Generic, all-purpose. Best used when the program cannot know how many times the block of code needs to repeat. – Repeats as long as CONDITION is true. for – A counting loop. Best used when the program knows how many times the block of code needs to repeat. Convenient for the programmer. 4

5 The while loop 1.General Structure 2.Ex1 & 2: validating 1 input 3.Ex3: validation +1 inputs 4.Ex4: Running totals 5.Infinite while loops 5

6 2. General Structure General construct layout: Initialization while condition 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 6 Loop Body

7 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 “SHOULD IT EXECUTE AGAIN?” (not “IS IT DONE?”) 7

8 while condition “Again?” vs. “Done?” Common English: I want some code to execute UNTIL the user provides the value of 0. Both of the following mean the same thing to us – but only one provides a condition that works correctly in MATLAB: “Done?”“Repeat UNTIL the value is 0” “Again?” “Repeat AS LONG AS the value is not 0” WHILE loops are like IF statements – the body is executed when the condition is True. 8

9 while condition How do we write the condition so that the WHILE loop body repeats when the condition is True ? The “Done?” thought process will QUIT when the condition is True : “Repeat UNTIL the value is 0” Pseudo-code: repeat until value==0 code value = input(…) end-of-repeat 9

10 while condition How do we write the condition so that the WHILE loop body repeats when the condition is True ? The “Again?” process will REPEAT when the condition is True : “Repeat AS LONG AS the value is NOT 0” Pseudo-code: repeat as long as value ~= 0 code value = input(…) end-of-repeat 10 NOT EQUAL

11 while condition How do we write the condition so that the WHILE loop body repeats when the condition is True ? Always think in these terms: “When do I want the code to execute again?” In this example: “I want some code to execute until the user provides the value of 0.” I want the code to execute again when … value ~= 0 Thus, we have our WHILE loop condition 11

12 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) – … 12

13 Ex1: Validating one input Checking for a particular input that must be between 0-100 (inclusive) % 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 13

14 Ex1: Validating one input Checking for a particular input that must be between 0-100 (inclusive) % 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'); 14 Never write the loop until the body works without it!

15 Ex1: Validating one input Checking for a particular input that must be between 0-100 (inclusive) % Initialize first reading reading = input('Enter reading (between 0-100): '); % Repeat as long as there is an error while reading 100 %Ask for reading again to update value reading = input('Re-enter reading (MUST be from 0-100'); end 15

16 Ex2: Numerous inputs Prompt the user for a width, height, and depth in inches. Compute the volume. Prompt again when invalid inputs. 16

17 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 volume of tank 17

18 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 % prompt for depth until valid % calculate volume of tank 18

19 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): '); while height <=0 height = input('ERROR: height strictly positive only --> '); end % prompt for depth until valid % calculate volume of tank 19

20 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): '); while height<=0 height = input('ERROR: height strictly positive only --> '); end % prompt for depth until valid depth = input('\nEnter a positive depth (inches): '); while depth<=0 depth = input('ERROR: depth strictly positive only --> '); end % calculate volume of tank volumeTankIn3 = width*height*depth; 20

21 Ex2, output 21

22 Why not all at once? Wouldn't it be easier to do this: Easier for you because it has fewer loops, but harder for the user. We force them to re-enter all of the values. 22

23 Ex3: Running Totals Ask user for a list of surfaces in m 2. Add all surfaces together. Stop asking when a negative/or null surface is entered! What is being done repeatedly? The program will repeatedly collect the area of a surface and add it to a total. What kind of loop? The program cannot know how many areas will be entered, so the number of times the loop will repeat is not known. Instead, the program must collect AS LONG AS (while) a strictly positive value is entered. 23

24 Ex4: Running Totals This code involves having a “RUNNING TOTAL”. 24

25 Ex4: Running Totals This code involves having a “RUNNING TOTAL”. “As the code RUNS, the TOTAL is repeatedly updated”. Note: each individual value (6,13,27) is not of any interest after it has been added in - so we're not going to try and save the individual values. 25 6 points 13 points 27 points Scoring Sheet. http://the.mcwessels.org/2009/09/ http://the.mcwessels.org/2009/09/

26 Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % prompt for first surface (and give directions) 26

27 Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % prompt for first surface (and give directions) % start result at zero 27

28 Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % prompt for first surface (and give directions) % start result at zero % As long as surface is positive 28

29 Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % prompt for first surface (and give directions) % start result at zero % As long as surface is positive % “running total”: add surfaces as they are given 29

30 Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % prompt for first surface (and give directions) % start result at zero % As long as surface is positive % “running total”: add surfaces as they are given % ask for next surface value 30

31 Ex4, algorithm Ask user for a list of surfaces in meters squared. Add all surfaces together. Stop asking when a negative/or null surface is entered! % start result at zero % get the first surface % As long as the current surface is positive % “running total”: add surface to total % ask for next surface value % display total surface to the screen 31

32 Ex4, initialization % start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) % As long as surface is positive % “running total”: add surfaces as they are given % ask for next surface value % display total surface to the screen 32

33 Ex4, initialization % start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive % “running total”: add surfaces as they are given % ask for next surface value % display total surface to the screen 33

34 Ex4, block of code %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value % display total surface to the screen 34

35 Ex4, change of condition %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); % display total surface to the screen 35

36 Ex4, fill in the code %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive while % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); end % display total surface to the screen 36

37 Ex4, condition %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive while surface>0 % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); end % display total surface to the screen 37

38 Ex4, continue %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive while surface>0 % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); end % display total surface to the screen fprintf('All surfaces add up to %.4f m^2.\n', sumSurfaces); 38

39 Ex4, output result 39

40 Ex4, the 3 criteria %start result at zero sumSurfaces = 0; % prompt for a surface (and give directions) fprintf('Note: a negative/zero surface quits.\n'); surface = input('Enter surface (m^2): '); % As long as surface is positive while surface>0 % “running total”: add surfaces as they are given sumSurfaces = sumSurfaces + surface; % ask for next surface value surface = input('Next surface: '); end % display total surface to the screen fprintf('All surfaces add up to %.4f m^2.\n', sumSurfaces); 40 INITIALIZATION UPDATE CONDITION Code to Repeat

41 Example: Infinite Loop A loop is said to be infinite if the body of the loop never stops repeating once it starts. It is caused by a loop condition that once true 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 41 x = input('Enter x: '); while x<0 input('ERROR: enter x again: '); end

42 Example: Infinite Loop Omitting semi-colons is a great way to know why a loop is infinite. 42 x = 10 while x>0 x = x + 1 end >> x = 10 x = 11 x = 12 x = 13

43 Example: Infinite Loop 43 x = input('Enter x: ') while x<0 input('ERROR: enter x again: '); end >> Enter x: -5 x = -5 ERROR: enter x again: 5 ERROR: enter x again:

44 Infinite loop Infinite Loop  Once the loop has 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 44

45 Infinite loop, cont. Is this an infinite loop in MATLAB? x = 10;% 1. initialization while (x > 10)% 2. condition fprintf('%02d\n', x); x = x + 1;% 3. change loop variable end 45 An infinite loop is not the same thing as a program that doesn't quit. You can have an infinite loop in a program that quits just fine. It is the loop that is infinite – not necessarily the program.

46 Key Ideas A while loop repeats a block of code as long as a condition is true. Structure: Initialization, while condition, code to be repeated, update of condition, end Common Uses: – trap the user until 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 becomes false from within the loop body. – To stop an infinite loop: Ctrl-C in the command window 46


Download ppt "Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1."

Similar presentations


Ads by Google