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

Post on 18-Jan-2018

227 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

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

1

Intro to Loops

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

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

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.

5

The while loop

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

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

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.

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

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

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

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

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

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!

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

Ex2: Numerous inputs

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

16

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

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

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

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

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.

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

Ex4: Running Totals

• This code involves having a “RUNNING TOTAL”.

24

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/

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

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

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

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

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

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

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

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

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

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

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

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

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

Ex4, output result

39

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

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

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

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:

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

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.

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

top related