intro to loops 1.general knowledge 2.two types of loops 3.the while loop 1

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

Upload: warren-hart

Post on 18-Jan-2018

227 views

Category:

Documents


0 download

DESCRIPTION

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

TRANSCRIPT

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

1

Intro to Loops

1. General Knowledge2. Two Types of Loops3. The WHILE loop

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

1. General Knowledge

• Loops are used to repeatedly execute lines of code.

• There are 2 basic uses for loops1. 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

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

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

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

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.

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

5

The while loop

1. General Structure2. Ex1 & 2: validating 1 input3. Ex3: validation +1 inputs4. Ex4: Running totals5. Infinite while loops

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

2. General Structure

• General construct layout:

Initializationwhile condition

Code you wish to repeatUpdate of conditionNote: In the block of code, the variables involved in the condition MUST be updated to avoid an infinite loop.

end

6

Loop Body

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

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

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

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.

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

9

while conditionHow 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

codevalue = input(…)

end-of-repeat

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

10

while conditionHow 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

codevalue = input(…)

end-of-repeat

NOT EQUAL

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

11

while conditionHow 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

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

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

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

Ex1: Validating one input

• Checking for a particular input that must be between 0-100 (inclusive)

%Initialize first readingreading = input('Enter reading (between 0-100): ');

% Repeat as long as there is an error

%Ask for reading again to update value

13

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

Ex1: Validating one input

• Checking for a particular input that must be between 0-100 (inclusive)

%Initialize first readingreading = 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!

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

Ex1: Validating one input

• Checking for a particular input that must be between 0-100 (inclusive)

%Initialize first readingreading = input('Enter reading (between 0-100): ');

% Repeat as long as there is an errorwhile reading<0 || reading>100

%Ask for reading again to update value reading = input('Re-enter reading (MUST be from 0-100');

end

15

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

Ex2: Numerous inputs

• Prompt the user for a width, height, and depth in inches. Compute the volume. Prompt again when invalid inputs.

16

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

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

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

Ex2, code

% prompt for width until validwidth = 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

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

Ex2, code

% prompt for width until validwidth = input('Enter a positive width (inches): ');while width<=0

width = input('ERROR: width strictly positive only --> ');end

% prompt for height until validheight = 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

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

Ex2, code

% prompt for width until validwidth = input('Enter a positive width (inches): ');while width<=0

width = input('ERROR: width strictly positive only --> ');end

% prompt for height until validheight = input('\nEnter a positive height (inches): ');while height<=0

height = input('ERROR: height strictly positive only --> ');end

% prompt for depth until validdepth = input('\nEnter a positive depth (inches): ');while depth<=0

depth = input('ERROR: depth strictly positive only --> ');end

% calculate volume of tankvolumeTankIn3 = width*height*depth;

20

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

Ex2, output

21

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

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.

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

Ex3: Running Totals

Ask user for a list of surfaces in m2. 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

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

Ex4: Running Totals

• This code involves having a “RUNNING TOTAL”.

24

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

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/

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

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

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

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

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

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

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

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

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

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

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

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

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

Ex4, initialization% start result at zerosumSurfaces = 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

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

Ex4, initialization% start result at zerosumSurfaces = 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

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

Ex4, block of code%start result at zerosumSurfaces = 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 givensumSurfaces = sumSurfaces + surface;

% ask for next surface value

% display total surface to the screen

34

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

Ex4, change of condition%start result at zerosumSurfaces = 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 givensumSurfaces = sumSurfaces + surface;

% ask for next surface valuesurface = input('Next surface: ');

% display total surface to the screen

35

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

Ex4, fill in the code%start result at zerosumSurfaces = 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 positivewhile

% “running total”: add surfaces as they are givensumSurfaces = sumSurfaces + surface;

% ask for next surface valuesurface = input('Next surface: ');

end

% display total surface to the screen

36

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

Ex4, condition%start result at zerosumSurfaces = 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 positivewhile surface>0

% “running total”: add surfaces as they are givensumSurfaces = sumSurfaces + surface;

% ask for next surface valuesurface = input('Next surface: ');

end

% display total surface to the screen

37

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

Ex4, continue%start result at zerosumSurfaces = 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 positivewhile surface>0

% “running total”: add surfaces as they are givensumSurfaces = sumSurfaces + surface;

% ask for next surface valuesurface = input('Next surface: ');

end

% display total surface to the screenfprintf('All surfaces add up to %.4f m^2.\n', sumSurfaces); 38

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

Ex4, output result

39

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

Ex4, the 3 criteria

%start result at zerosumSurfaces = 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 positivewhile surface>0

% “running total”: add surfaces as they are givensumSurfaces = sumSurfaces + surface;

% ask for next surface valuesurface = input('Next surface: ');

end

% display total surface to the screenfprintf('All surfaces add up to %.4f m^2.\n', sumSurfaces);

40

INITIALIZATION

UPDATE

CONDITION

Code to Repeat

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

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

• Examplesx = 10;while x>0

x = x + 1;end

41

x = input('Enter x: ');while x<0 input('ERROR: enter x again: ');end

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

Example: Infinite Loop

• Omitting semi-colons is a great way to know why a loop is infinite.

42

x = 10while x>0

x = x + 1end

>>>>x = 10

x = 11

x = 12

x = 13

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

Example: Infinite Loop

43

x = input('Enter x: ')while x<0 input('ERROR: enter x again: ');end

>>>>Enter x: -5x = -5

ERROR: enter x again: 5

ERROR: enter x again:

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

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

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

Infinite loop, cont.

• Is this an infinite loop in MATLAB?

x = 10; % 1. initializationwhile (x > 10) % 2. condition

fprintf('%02d\n', x);x = x + 1; % 3. change loop

variableend

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.

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

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