control structures - repetition chapter 5 2 chapter topics why is repetition needed the repetition...

34
Control Structures - Repetition Chapter 5

Upload: shauna-chase

Post on 24-Dec-2015

250 views

Category:

Documents


6 download

TRANSCRIPT

Page 1: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

Control Structures - Repetition

Chapter 5

Page 2: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

2

Chapter Topics

Why Is Repetition Needed

The Repetition Structure

Counter Controlled Loops

Sentinel Controlled Loops

Flag Controlled Loops

EOF Controlled Loops

forfor Loops

The do … while do … while Looping Structure

Page 3: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

3

Why Is Repetition Needed?

Consider a task that the computer might automate

Calculate and print paychecks

Read invoices from a file and print monthly statements

Read inputs from a sensor and adjust the air-fuel mixture of an engine

In generalThe "Input – process – output" cycle

Page 4: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

4

Why Is Repetition Needed?

The algorithm requires a set of actions to be done over and over again

Same set of actions

Number of times to be executed is unknown at design time

We need a structure which allowsStatement(s) to be repeated

A method of testing to see whether the statements should be repeated

Page 5: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

5

The Repetition Structure

The while while loopprovides therepetition structure

Statement(s) tobe repeated

A means of checking whether the statement(s) will be repeated

Syntax: while ( logicalExpression )while ( logicalExpression )

statement; statement;

Page 6: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

6

Phases of Loop Execution

Loop entry => flow of control reaches first statement inside loop

Iteration => each pass thru the loop

Loop test => condition tested before each iteration

Loop exit => when termination condition occurs

in while statement, loop is NOT executed another time

while (condition)

statement 1

statement 2

truefalse

Page 7: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

7

While Loop Illustration

Loop EntryLoop Entry

Loop TestLoop Test

Loop IterationLoop Iteration

Loop ExitLoop Exit

Page 8: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

8

Counter Controlled Loops

For when you know exactly how many times the loop should run

There are 10 employees for which to print checks

There are 60 sensor inputs per second

The program needs a Loop Control Variable

Page 9: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

9

Count Controlled Loop

Uses a Loop Control Variable (LCV)

x = 0;while (x <= 10) { cout << “count = “ << x << endl; x = x + 1; }

x = 0;while (x <= 10) { cout << “count = “ << x << endl; x = x + 1; }

What gets printed?What gets printed?

Page 10: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

10

Count Controlled Loops

I nitialized

I ncremented

I nspected

The LCV must be ...The LCV must be ...

Amen

Page 11: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

11

Count Controlled Loops

x = 0;while (x <= 10) { cout << “count = “ << x << endl; x = x + 1; }

x = 0;while (x <= 10) { cout << “count = “ << x << endl; x = x + 1; }

Initialized

Incremented

Inspected

Page 12: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

12

Sentinel Controlled Loops

Suppose you want to read some positive integers and average them

You do not have a preset number of data items in mind.

Suppose the number –999 –999 marks the end of data.

Then the -999-999 is your "sentinel"

cin>>variable;while(variable != sentinel){ . . .

cin>> variable;}

View sample program

Page 13: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

13

Flag Controlled Loops

A flag controlled loop uses a Boolean variable to control the loopExampleLet found found be the Boolean variablefound = false;found = false;

while(!found)while(!found){ . . .{ . . .

if(expression)if(expression) found = true;found = true; }}

The flag is set according to some

condition

Page 14: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

14

EOF Controlled Loops

End of File Controlled

Do you need to know how many items are in the file? Why? Why not?

Do you need to know how many items are in the file? Why? Why not?

Page 15: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

15

Testing the State of an I/O Stream

The name of the input stream (used by itself) returns a value

returns a 0 if it is NOT successful

it returns a NON zero value if it IS successful

Page 16: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

16

Testing the State of an I/O Stream

When reading a file (a named input stream) we wish to know when it reaches the end

Since the name returns a 0 or non-0, this can be used as a Boolean value

Used to control program sequencing, control a file reading loop

Page 17: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

17

EOF Controlled Loops

Can also be used in keyboard entry situationscin>>variable;cin>>variable;while(cin)while(cin){ . . .{ . . .

cin>>variable; // Ctrl-Z to signify cin>>variable; // Ctrl-Z to signify eofeof}}

Although a sentinel controlled loop might be more user friendly

Page 18: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

18

EOF Controlled Loops

In addition to checking the value of an input stream variable …

The function eof eof with an input stream variable can also be used to determine the end of file status.

Syntax: istreamVar.eof() istreamVar.eof()

Example infile.get(ch);infile.get(ch);while(!infile.eof())while(!infile.eof()){{ cout<<ch;cout<<ch; infile.get(ch);infile.get(ch);}}

Page 19: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

19

A Special Count Controlled Loop

The for ( … ) for ( … ) statement

Initialization : initializes the LCV

Condition : usually a comparison, acts like a while ( …)

Incrementing statement : LCV is incremented (or decremented)

for ( initialization ; test expression ; update ) {

0 or more statements to repeat}

for ( initialization ; test expression ; update ) {

0 or more statements to repeat}

Page 20: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

20

The for ( … )for ( … ) Loop

Example -- what gets printed?

•x gets initialized

•value of x inspected

•x gets incremented

How did it Happen?

Page 21: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

21

The for ( … )for ( … ) Loop

All three of the portions inside the parentheses can be multiple statements separated by commas

Any or all of the three portions inside the parenthesis may be missing

accomplish those tasks some other way

the two semicolons MUST be there

Page 22: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

22

forfor Loops

Note the sequence of events in a for for loop

Is it possible that the initialization and condition could be set so that that the loop statement would never execute?

Page 23: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

23

A Different Looping Statement

Recall that the while ( … ) while ( … ) statement always checked the condition BEFORE the loop

In certain situations wewish to check the condition at …

The END ofthe loop

After the statement

Page 24: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

24

The Do-While Statement

Condition tested at end/bottom of loop

Guarantees loop body executes at least once

Page 25: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

25

The do-while Illustrated

Loop EntryLoop EntryLoop IterationLoop Iteration

Loop ExitLoop Exit

Loop TrestLoop Trest

Note: alwaysat least one

iteration

Page 26: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

26

The Do-While Statement

Can be used for a counting loop

What gets printed??How do you change it to go 10 times?

Page 27: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

27

The Do While Statement

This logic sometimes more suitable for some algorithms

Example : trap for valid input

do { cout << “Enter value (1 - 5) -> “; cin >> value; if (value < 1 || value > 5) cout << “Invalid input\a” << endl; while (value < 1 || value > 5);

do { cout << “Enter value (1 - 5) -> “; cin >> value; if (value < 1 || value > 5) cout << “Invalid input\a” << endl; while (value < 1 || value > 5);

What makes this easier than the while ( … ) loop for this task?

What makes this easier than the while ( … ) loop for this task?

Page 28: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

28

do-while do-while Loop vs. whilewhile Loop

POST-TEST loop (exit-condition)

The looping condition is tested after executing the loop body.

Loop body is always executed at least once.

PRE-TEST loop (entry-condition)

The looping condition is tested before executing the loop body.

Loop body may not be executed at all.

Page 29: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

29

The break;break; Statement

We saw it in the switch switch statement

Causes immediate exit from innermost block

switchswitch, whilewhile, do-whiledo-while, forfor

Can be used to break out of purposely designed infinite loop

not a good idea … a lazy shortcut

Use only as last resort to avoid baffling combinations of multiple Boolean flags and nested ifs

Page 30: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

30

The continue;continue; Statement

Valid only in loops

Terminates current loop iterationNOT entire loop

Causes branch to bottom of loopskips rest of loop statements

Loop then prepares for next iteration

for (…) for (…) would increment lcv

all loops would check condition

Page 31: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

31

Guidelines for Choosing a Looping Statement

Simple count-controlleduse for (…) for (…) loop

Event controlled, body always executed at least once

use do-whiledo-whileEvent controlled and nothing known about first execution

use whilewhile, possibly forforWhen in doubt => use whilewhile

Page 32: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

32

Testing and Debugging

For do-whiledo-while loops, make sure to try data sets to make loop go exactly one time

For data-dependant loop where expressions based on values other than constants

make sure to test for proper number of iterations

Make sure switch statements have every branch tested

including default

Page 33: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

33

Testing and Debugging

Remember to use break at end of case alternatives in switch statements

otherwise next case is also executed!

Case labels in switch statement must be values or named constants -- no variables

Both switch expression & case constant cannot be floating point

Provide default for switch when possibility of case values not being matched

Page 34: Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled

34

Testing and Debugging

Make sure all needed switch cases are present

Choose looping structure carefully

for( ; ; ) for( ; ; ) loop heading must have two semicolons -- even if portions omitted

Break statement can exit only one level of nesting

innermost switch or loop where break is located