looping - cs.csi.cuny.edu filelooping. 2 what is a loop? a loop is a repetition control structure...

Post on 01-Apr-2019

220 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

LoopingLooping

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

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

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

5

While StatementSYNTAX

while (Expression){ .

. // loop body

.}

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

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

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?

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

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

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

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

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

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;

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

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

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;

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

18

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

Boolean flag

while(isSafe){

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

isSafe = false; // change flag valueelse

countGoodReadings++;

19

Common Loop Uses

Count all data values

Count special data values

Sum data values

Keep track of current and previous values

20

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

initialize inner loopwhile(inner loop condition){

inner loop processing and update}. . .

}

Nested Loops

20

21

dodo--while Loop Syntax: while Loop Syntax:

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!

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"

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

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

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

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!

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

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

30

4567 1522318 1905232 151

. .

. .

. .There were 432 patients in file.

Read the data and display a chart

Patient ID BP Average

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

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

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

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

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

36

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

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

return 0;

}

top related