Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?

Similar presentations


Presentation on theme: "Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?"— Presentation transcript:

1 Chapter 6 Looping

2 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?

3 3 Two Types of Loops count controlled loops repeat a specified number of times event-controlled loops some condition within the loop body changes and this causes the repeating to stop

4 4 While Statement SYNTAX while ( Expression ) {.. // loop body. } NOTE: Loop body can be a single statement, a null statement, or a block.

5 5 When the expression is tested and found to be false, the loop is exited and control passes to the statement which follows the loop body. WHILE LOOP FALSE TRUE body statement Expression

6 6 an initialization of the loop control variable an expression to test for continuing the loop an update of the loop control variable to be executed with each iteration of the body Count-controlled loop contains

7 7 int count ; count = 4; // initialize loop variable while (count > 0) // test expression { cout << count << endl ; // repeated action count -- ; // update loop variable } cout << “Done” << endl ; Count-controlled Loop

8 8 int count ; count = 4; while (count > 0) { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT count

9 9 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT count 4

10 10 Count-controlled Loop int count ; count = 4; while (count > 0) TRUE { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT count 4

11 11 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 count 4

12 12 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 count 3

13 13 Count-controlled Loop int count ; count = 4; while (count > 0) TRUE { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 count 3

14 14 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 3 count 3

15 15 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 3 count 2

16 16 Count-controlled Loop int count ; count = 4; while (count > 0) TRUE { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 3 count 2

17 17 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 3 2 count 2

18 18 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 3 2 count 1

19 19 Count-controlled Loop int count ; count = 4; while (count > 0) TRUE { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 3 2 count 1

20 20 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 3 2 1 count 1

21 21 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 3 2 1 count 0

22 22 Count-controlled Loop int count ; count = 4; while (count > 0) FALSE { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 3 2 1 count 0

23 23 Count-controlled Loop int count ; count = 4; while (count > 0) { cout << count << endl ; count -- ; } cout << “Done” << endl ; OUTPUT 4 3 2 1 Done count 0

24 24 myInfile contains 100 blood pressures Use a while loop to read the 100 blood pressures and find their total Count-Controlled Loop Example

25 25 ifstream myInfile ; int thisBP ; int total ; int count ; count = 0 ; // initialize myInfile.open(“bp.txt”); while ( count < 100 ) // test expression { myInfile >> thisBP ; total = total + thisBP ; count++ ; // update } cout << “The total = “ << total << endl ; 25

26 26 Event-controlled Loops l Sentinel controlled keep processing data until a special value which is not a possible data value is entered to indicate that processing should stop l End-of-file controlled keep processing data as long as there is more data in the file l Flag controlled keep processing data until the value of a flag changes in the loop body 26

27 27 Examples of Kinds of Loops Count controlled loop Read exactly 100 blood pressures from a file. End-of-file controlled loop Read all the blood pressures from a file no matter how many are there. 27

28 28 Examples of Kinds of Loops Sentinel controlled loop Read blood pressures until a special value (like -1) selected by you is read. Flag controlled loop Read blood pressures until a dangerously high BP (200 or more) is read. 28

29 29 A Sentinel-controlled Loop l requires a “priming read” l “priming read” means you read one set of data before the while

30 30 // Sentinel controlled loop total = 0; int thisBP; 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;

31 31 End-of-File Controlled Loop l depends on fact that a file goes into fail state when you try to read a data value beyond the end of the file

32 32 total = 0; int thisBP; // Read first value in file myInfile >> thisBP;// Red first value // While read is successful while (myInfile) // while last read successful { total = total + thisBP; // Process this read myInfile >> thisBP; // next read } cout << total; // End-of-file controlled loop

33 33 //End-of-file at keyboard total = 0; int thisBP; 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;

34 34 Flag-controlled Loops l you initialize a flag (to true or false) l use meaningful name for the flag l a condition in the loop body changes the value of the flag l test for the flag in the loop test expression

35 35 countGoodReadings = 0; bool isSafe = true; // initialize Boolean flag int thisBP; while (isSafe) { cin >> thisBP; if ( thisBP >= 200 ) isSafe = false; // change flag value else countGoodReadings++; } cout << countGoodReadings << endl;

36 36 initialize outer loop while ( outer loop condition ) {... initialize inner loop while ( inner loop condition ) { inner loop processing and update }... } Pattern of a Nested Loop 36

37 37 Patient Data A 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 howManyReadings 4567 5180 140 150 170 120 23182170 210 52323150 151 151

38 38 4567152 2318190 5232151.. There were 432 patients in file. Read the data and display a chart Patient ID BP Average

39 39 Algorithm Uses Nested Loops l initialize patientCount to 0 l read first ID and howMany from file l while not end-of-file n increment patientCount n display ID n use a count-controlled loop to read and sum up this patient’s howMany BP’s n calculate and display average for patient n read next ID and howMany from file l display patientCount

40 40 To design a nested loop l begin with outer loop l when you get to where the inner loop appears, make it a separate module and come back to its design later

41 41 #include #include using namespace std; int main ( ) { int patientCount; // declarations int thisID; int howMany; int thisBP; int totalForPatient; int count; float average; ifstream myInfile; 41

42 42 myInfile.open(“BP.txt”); if (!myInfile ) // opening failed { cout > thisID >> howMany; // first read 42

43 43 while ( myInfile ) // last read successful { patientCount++; cout << thisID; totalForPatient = 0; // initialize inner loop count = 0; while ( count < howMany) { myInfile >> thisBP; count ++; totalForPatient = totalForPatient + thisBP; } average = totalForPatient / float(howMany); cout <<“\t\t”<< int (average +.5) << endl; // round myInfile >> thisID >> howMany; // another read } 43

44 44 cout << “There were “ << patientCount << “ patients on file.” << endl; cout << “Program terminated.\n”; return 0; }

45 45 Example of three ways to read file data l First line contains the number of lines to read l The last line of the file contains a sentinel l Read until end of file (EOF) - best

46 46 Information About Books in Diskfile “books.txt” 3.98 P 7.41 H 8.79 P. Price of book Hardback or Paperback? WRITE A PROGRAM TO FIND TOTAL VALUE OF ALL BOOKS

47 47 #include // for cout #include // for file I/O using namespace std; int main (void) { float price ; // declarations char kind ; ifstream myInfile ; float total = 0.0 ; int count = 1; int lines; Three examples of file reading

48 48 Open the file string books = "books1.txt"; myInfile.open(books.c_str()) ; if (!myInfile) { cout << "Error opening " << books << endl; return 1; } 48

49 49 First line has number of lines to read // count-controlled processing loop // First line of file contains number of lines myInfile >> lines; while ( count <= lines) { myInfile >> price >> kind ; total = total + price ; count ++ ; } cout << "Total is: " << total << endl ; myInfile.close( ) ; return 0 ; } 49

50 50 Last line has sentinel (-1) // sentinel-controlled processing loop myInfile >> price >> kind; while (price != -1) { total = total + price ; // Process count ++ ; myInfile >> price >> kind ; // Read next line } cout << "Total is: " << total << endl ; myInfile.close( ) ; return 0 ; } 50

51 51 Read until EOF (Best) // EOF controlled processing loop myInfile >> price >> kind; // read 1st line while (myInfile) // true until EOF { total = total + price ; // Process line count ++ ; myInfile >> price >> kind ; // read next line } cout << "Total is: " << total << endl ; myInfile.close( ) ; return 0 ; } 51

52 52 Loop Testing and Debugging test data should test all sections of program l beware of infinite loops -- program doesn’t stop l check loop termination condition, and watch for “off-by-1” problem l use get function for loops controlled by detection of ‘\n’ character l use algorithm walk-through to verify pre- and postconditions l trace execution of loop by hand with code walk-through l use a debugger to run program in “slow motion” or use debug output statements


Download ppt "Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?"

Similar presentations


Ads by Google