Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure...

36
Looping Looping

Transcript of Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure...

Page 1: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

LoopingLooping

Page 2: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

2

What is a loop?

A loop is a repetition control structure that causes a single statement or block to be executed repeatedly

Loops

Page 3: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

3

LoopsLoops3 Types of loops in C++

while– Most flexible– No "restrictions"

do-while– Least flexible– Always executes loop body at least once

for– Natural "counting" loop

Page 4: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

4

Two Types of Loops

Count controlled loopsRepeat a statement or block a specified number of times

Event-controlled loopsRepeat a statement or block until a condition within the loop body changes that causes the repetition to stop

Page 5: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

5

While StatementSYNTAX

while (Expression){ .

. // loop body

.}

Loop body can be a single statement, a null statement, or a block

Page 6: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

6

When the expression is tested and found to be false, the loop is exited and control passes to the statement that follows the loop body

WHILE LOOPFALSE

TRUE

bodystatement

Expression

Page 7: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

7

while Loop Examplewhile Loop Example

Consider:count = 0; // Initializationwhile (count < 3) // Loop Condition{

cout << "Hi "; // Loop Bodycount++; // Update

expression}

Loop body executes how many times?

Page 8: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

8

Count-controlled loops containAn initialization of the loop control variableAn expression to test if the proper number of repetitions has been completedAn update of the loop control variable to be executed with each iteration of the body

Count-Controlled Loops

Page 9: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

9

int count; // Loop-control variable

count = 4; // assign a value to loop variable

while(count > 0) // Test expression{

cout << count << endl; // Repeated action

count --; // Update loop variable}cout << “Done” << endl;

Count-Controlled Loop Example

Page 10: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

10

Types of Event-Controlled Loops

Sentinel controlledKeep processing data until a special value that

is not a possible data value is entered to indicate that processing should stop

End-of-file controlledKeep processing data as long as there is more

data in the file

Flag controlledKeep processing data until the value of a flag

changes in the loop body 10

Page 11: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

11

Examples of Kinds of Loops

Count controlled loop Read exact number of values from a file

End-of-file controlledloop

Read all values from a file no matter how many are there

11

Page 12: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

12

Examples of Kinds of Loops

Sentinel controlled loop

Read values until a special value selected by you (like -1) is read

Flag controlledloop

Read values until a dangerously value is read

12

Page 13: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

13

// Sentinel controlled loop

total = 0;cout << “Enter a blood pressure(-1 to stop) ”;cin >> thisBP;

while (thisBP != -1)// While not sentinel{

total = total + thisBP;cout << “Enter a blood pressure (-1 to stop)”;

cin >> thisBP;}cout << total;

Page 14: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

14

End-of-File Controlled Loop

Uses the fact that a file goes into the fail state when you try to read a data value beyond the end of the file to control the loop

Page 15: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

15

total = 0;

myInfile >> thisBP; // priming read

while(myInfile) // while last read successful{

total = total + thisBP;myInfile >> thisBP; // read another

}

cout << total;

// End-of-file controlled loop

Page 16: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

16

// End-of-file at keyboard

total = 0;cout << “Enter blood pressure “

<< “(Ctrl-Z to stop)”;cin >> thisBP; // Priming read

while(cin) // While last read successful{

total = total + thisBP;cout << “Enter blood pressure”;cin >> thisBP; // Read another

}cout << total;

Page 17: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

17

Flag-controlled Loops

Initialize a flag(to true or false)Use meaningful name for the flagA condition in the loop body changes the value of the flagTest for the flag in the loop test expression

Page 18: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

18

countGoodReadings = 0;isSafe = true; // assign a value to

Boolean flag

while(isSafe){

cin >> thisBP;if (thisBP >= 200)

isSafe = false; // change flag valueelse

countGoodReadings++;

Page 19: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

19

Common Loop Uses

Count all data values

Count special data values

Sum data values

Keep track of current and previous values

Page 20: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

20

initialize outer loopwhile (outer loop condition){ . . .

initialize inner loopwhile(inner loop condition){

inner loop processing and update}. . .

}

Nested Loops

20

Page 21: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

21

dodo--while Loop Syntax: while Loop Syntax:

Page 22: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

22

dodo--while Loop Examplewhile Loop Example

int count = 0; // Initializationdo {

cout << "Hi "; // Loop Bodycount++; // Update expression

} while (count < 3); // Loop ConditionLoop body executes how many times?

do-while loops always execute body at least once!

Page 23: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

23

while vs. do-whileVery similar, but…

One important difference– Issue is "WHEN" boolean expression is checked– while:checks BEFORE body is executed– do-while: checked AFTER body is executed

After this difference, they’re essentially identical!

while is more common, due to it’s ultimate "flexibility"

Page 24: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

24

for Loop Syntaxfor Loop Syntax

for (Init_Action; Bool_Exp; Update_Action)Body_Statement

Like if-else, Body_Statement can bea block statement

Much more typical

Page 25: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

25

for Loop Examplefor Loop Example

for (count=0;count<3;count++) {

cout << "Hi "; // Loop Body}

How many times does loop body execute?

Initialization, loop condition and update all"built into" the for-loop structure!

A natural "counting" loop

Page 26: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

26

Nested LoopsNested Loops

Requires careful indenting:

for (outer=0; outer<5; outer++)for (inner=7; inner>2; inner--)

cout << outer << inner;

Notice no { } since each body is one statement

Page 27: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

27

The break and continue StatementsThe break and continue Statementsbreak;

Forces loop to exit immediately.

continue;Skips rest of loop body

These statements violate natural flowOnly used when absolutely necessary!

Page 28: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

28

SummarySummarydo-while loops

Always execute their loop body at least once

for-loopA natural "counting" loop

Loops can be exited earlybreak statementcontinue statementUsage restricted for style purposes

Page 29: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

29

Patient DataA file contains blood pressure data for different people. Each line has a patient ID, the number of readings for that patient, followed by the actual readings.

ID howMany Readings

4567 5 180 140 150 170 1202318 2 170 2105232 3 150 151 151

Page 30: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

30

4567 1522318 1905232 151

. .

. .

. .There were 432 patients in file.

Read the data and display a chart

Patient ID BP Average

Page 31: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

31

Algorithm

Initialize patientCount to 0Read first ID and howMany from fileWhile not end-of-file

Increment patientCountDisplay IDRead and sum this patient’s BP’sCalculate and display average for patientRead next ID and howMany from file

display patientCount

Page 32: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

32

Designing Nested LoopsDesigning Nested Loops

Begin with outer loop

When you get to where the inner loop appears, make it a separate module and come back to its design later

Page 33: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

33

#include <iostream>#include <fstream>using namespace std;

int main( ){

int patientCount; // Declarationsint thisID;int howMany;int thisBP;int totalForPatient;int count;

float average;ifstream myInfile;

33

Page 34: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

34

myInfile.open(“BP.dat”);

if (!myInfile) // Opening failed{

cout << “File opening error. Program terminated.”;

return 1;}

cout << “ID Number Average BP” << endl;

patientCount = 0;

myInfile >> thisID >> howMany; // Priming read

34

Page 35: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

35

while(myInfile) // Last read successful{

patientCount++;cout << thisID;totalForPatient = 0; // Unitialize inner loop

count = 0;while(count < howMany){

myInfile >> thisBP;count ++;totalForPatient =

totalForPatient + thisBP;}

average = totalForPatient / float(howMany);cout << int(average + .5) << endl;// Another readmyInfile >> thisID >> howMany;

} 35

Page 36: Looping - cs.csi.cuny.edu fileLooping. 2 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops. 3 Loops z3

36

cout << “There were “ << patientCount<< “patients on file.” << endl;

cout << “Program terminated.” << endl;

return 0;

}