Programming and Problem Solving with C++, 2/e

Programming and Problem Solving with C++, 2/e

Chapter 6 Looping Chapter 6 Topics While Statement Syntax Count-Controlled Loops Event-Controlled Loops Using the End-of-File Condition to Control Input Data Chapter 6 Topics

Using a While Statement for Summing and Counting Nested While Loops Loop Testing and Debugging Loops What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Two Types of Loops Count controlled loops Repeat a statement or block a specified number of times Event-controlled loops Repeat a statement or block until a condition within the loop body changes

that causes the repetition to stop While Statement SYNTAX while (Expression) { . . // loop body . } Loop body can be a single statement, a null statement, or a block 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 LOOP FALSE Expression TRUE body statement Count-Controlled Loops Count-controlled loops contain: An initialization of the loop control variable An expression to test if the proper number of repetitions has been completed An update of the loop control variable to be executed with each iteration of the

body Count-Controlled Loop Example int count; count = 4; // Loop-control variable // Initialize loop variable while(count > 0) // Test expression {

cout << count << endl; // Repeated action count --; } cout // Update loop variable << Done << endl; Count-controlled Loop int count count; count =

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

count; count = 4 4; while(count > 0) { cout << count << endl; count --; } cout

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

} cout count << Done << endl; 4 OUTPUT Count-controlled Loop int count; count = count

4; while(count > 0) { cout << count 4 << endl; count --; } cout << Done << endl; OUTPUT 4 Count-controlled Loop

int count count; count = 4; while(count > 0) { cout << count 3 << endl;

count --; } cout << Done << endl; OUTPUT 4 Count-controlled Loop int count count; count =

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

count; count = count 4; while(count > 0) { cout << count 3 << endl; count --; } cout

OUTPUT 4 3 << Done << endl; Count-controlled Loop int count count; count = 2

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

count count; count = 2 4; while(count > 0) TRUE { cout << count << endl; count --; } cout

<< Done << endl; OUTPUT 4 3 Count-controlled Loop int count count; count = 2 4;

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

count count; count = 4; while(count > 0) { cout << count 1 << endl; count --;

} cout << Done << endl; OUTPUT 4 3 2 Count-controlled Loop int count count; count =

1 4; while(count > 0) TRUE { cout << count count --; } cout OUTPUT << endl; << Done << endl;

4 3 2 Count-controlled Loop int count count; count = 1 4;

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

int count count; count = 0 4; while(count > 0) { cout << count << endl;

count --; } cout << Done << endl; OUTPUT 4 3 2 1 Count-controlled Loop int count count; count

= 0 4; while(count > 0) FALSE { cout << count << endl; count --; } cout << Done << endl; OUTPUT 4 3 2

1 Count-controlled Loop count int count; count = 0 4; while(count > 0) { cout << count

<< endl; count --; } cout << Done << endl; OUTPUT 4 3 2 1 Done Example myInfile contains 100 blood pressures Use a while loop to read the 100 blood pressures and find their total

ifstream int int int count = 0; myInfile; thisBP; total; count; // Initialize while (count < 100) // Test expression { myInfile >> thisBP; total = total + thisBP; count++; // Update

} cout << The total = << total << endl; Types of Event-Controlled Loops Sentinel controlled Keep processing data until a special value that

is not a possible data value is entered to indicate that processing should stop End-of-file controlled Keep processing data as long as there is more data in the file Flag controlled Keep processing data until the value of a flag changes in the loop body 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 Examples of Kinds of Loops Sentinel controlled loop Read blood pressures until a special value selected by you(like -1) is read Flag controlled

loop Read blood pressures until a dangerously high BP(200 or more) is read A Sentinel-controlled Loop Requires a priming read A priming read is the reading of one set of data before the loop to initialize the variables in the expression // Sentinel controlled loop total = 0;

cout << Enter a blood pressure(-1 to stop) ; cin >> thisBP; // Sentinel controlled loop, cont... while(thisBP != -1) // While not sentinel { total = total + thisBP; cout << Enter a blood pressure(-1 to stop); cin >> thisBP; } cout << total; 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 // End-of-file controlled loop total = 0; myInfile >> thisBP; // Priming read // End-of-file controlled loop, cont... while(cin) // While last read successful { total = total + thisBP; cout << Enter blood pressure; cin >> thisBP;

// Read another } cout << total; // End-of-file at keyboard total = 0; cout cin << Enter blood pressure << (Ctrl-Z to stop); >> thisBP; // Priming read // End-of-file at keyboard, cont... while(cin) // While last read successful { total = total + thisBP;

cout << Enter blood pressure; cin >> thisBP; // Read another } cout << total; Flag-controlled Loops Initialize a flag (to true or false) Use meaningful name for the flag A condition in the loop body changes the value of the flag Test for the flag in the loop test expression Example of Flag-controlled Loop countGoodReadings = 0; isSafe = true; // Initialize Boolean flag while(isSafe)

{ cin >> thisBP; if (thisBP >= 200) isSafe = false; // Change flag value Example, continued else countGoodReadings++; } cout << countGoodReadings << endl;

Common Loop Uses Count all data values Count special data values Sum data values Keep track of current and previous values Current and Previous Values

Write a program that counts the number of != operators in a program file Read one character in the file at a time Keep track of current and previous characters Keeping Track of Values previous (x != 3) { cout << endl; } FILE CONTENTS

current count ( x 0 x 0 !

0 ! = 1 = 1 3 1

3 ) 1 Loop Program Keeping Track of Current and Previous Values int char char count; previous; current; count = 0; inFile.get(previous); inFile.get(current);

// Priming reads Keeping Track of Current and Previous Values , continued while(inFile) { if((current == =) && (previous == !)) count++; previous = current; // Update inFile.get(current); // Read another } Nested Loops initialize outer loop while (outer loop condition) { ...

initialize inner loop while(inner loop condition) { inner loop processing and update } ... } 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 howMany Readings 4567 2318 5232 5 180 140 150 170 120 2 170 210

3 150 151 151 Read the data and display a chart Patient ID BP Average 4567 152 2318 190 5232 151 . . . . . . There were 432 patients in file.

Algorithm Initialize patientCount to 0 Read first ID and howMany from file Algorithim, cont... While not end-of-file Increment patientCount Display ID Read and sum this patients BPs Calculate and display average for patient Read next ID and howMany from file Display patientCount Designing 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 Designed Nested Loop Example #include #include using namespace std; Designed Nested Loop Example int { main() int int int int

int int patientCount; // Declarations thisID; howMany; thisBP; totalForPatient; count; float average; ifstream myInfile; Designed Nested Loop Example, cont.... 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 Designed Nested Loop Example, cont.... while(myInfile) // Last read successful { patientCount++; cout << thisID; totalForPatient = 0; // Initialize inner loop count = 0; while(count < howMany) { myInfile >> thisBP; count ++;

totalForPatient = totalForPatient + thisBP; } Designed Nested Loop Example, cont.... average = totalForPatient / float(howMany); cout << int(average + .5) << endl; // Another read myInfile >> thisID >> howMany; } cout << << There were << patientCount patients on file. << endl; cout << return 0; }

Program terminated. << endl; Information About 20 Books in Diskfile myIn.dat Price of book Hardback or Paperback? 3.98 P 7.41 H 8.79 P . . . Write a program to find total value of all books

C++ Program #include #include // Access cout // Access file I/O using namespace std; int { main(void) float char ifstream float int price;

// Declarations kind; myInfile; total = 0.0; count = 1; C++ Program, cont... myInfile.open(myIn.dat); // count-controlled processing loop while( count <= 20) { myInfile >> price >> kind; total = total + price; count ++; } cout << Total is: << total << endl; myInfile.close(); return 0; }

Trace of Program Variables count price kind 0.0 1 2 3 4 20 21 3.98 7.41 8.79 etc.

P H P 3.98 11.39 20.18 so loop terminates total Complexity Complexity is a measure of the amount of work involved in executing an algorithm relative to the size of the problem

Polynomial Times N N0 N1 constant linear N2 N3 quadratic cubic 1 1

1 1 1 10 1 10 100 1,000 100 1

100 10,000 1,000,000 1,000 1 1,000 1,000,000 1,000,000,000 10,000 1

10,000 100,000,000 1,000,000,000,000 Loop Testing and Debugging Test data should test all sections of program Beware of infinite loops -- program doesnt stop Check loop termination condition, and watch for off-by-1 bugs(OBOBs)

Use get function for loops controlled by detection of \n character Loop Testing and Debugging Use algorithm walk-through to verify preand post conditions Trace execution of loop by hand with code walk-through Use a debugger to run program in slow motion or use debug output statements

Recently Viewed Presentations

  • Sources of Knowledge 1 Knowledge Sources: Socal Scientific

    Sources of Knowledge 1 Knowledge Sources: Socal Scientific

    Positivism vs. Intrepretative Prefer quantitative approach Science discovers what exists Deduction Prefer qualitative approach Science helps create social reality Induction * Induction Inductive reasoning involves inferring something about a whole group or class of objects from our knowledge of one...
  • Adjectives &amp; Adverbs

    Adjectives & Adverbs

    Irregular Adjectives & Adverbs Comparative and Superlative forms of the irregular adjectives and adverbs are also irregular. Good & Well have the same comparative & superlative forms: Better (comparative) I have a better car than she does. (adjective) I feel...
  • 4.2 Apply Congruence and Triangles

    4.2 Apply Congruence and Triangles

    Side-ANGLE-side (sAs) Congruent Postulate If two sides and the included angle of one triangle are congruent to two sides and the included angle of a second triangle, Then the two triangles are congruent.
  • PowerPoint-Präsentation

    PowerPoint-Präsentation

    a systematic weakening and dismantling of multi-employer bargaining (at national and/or sectoral level) a dramatic decline of the bargaining coverage a strong downward pressure on wages leading to a deflationary spiral of wage competition with detrimental effects on consumer demand...
  • Supercomputing in Plain English: Teaching HPC

    Supercomputing in Plain English: Teaching HPC

    Supercomputing in Plain English Teaching High Performance Computing to Inexperienced Programmers Henry Neeman, University of Oklahoma Julia Mullen, Worcester Polytechnic Institute Lloyd Lee, University of Oklahoma Gerald K. Newman, University of Oklahoma This work was partially funded by NSF-0203481.
  • Chapter 7 Membrane Structure and Function

    Chapter 7 Membrane Structure and Function

    most abundant lipid in the plasma membrane. amphipathic. molecules, containing hydrophobic and hydrophilic regions. J. Singer & G. Nicolson (1972) proposed that the membrane is a mosaic of proteins dispersed within the bilayer, with only the hydrophilic regions exposed to...
  • FAA Organizational Framework for UAS Integration - aeronet.aero

    FAA Organizational Framework for UAS Integration - aeronet.aero

    Lead-up to the FAA UAS Integration Office. Pre-2013: FAA "Line of Business" Organizations (i.e. AIR, AFS, ATO) and Program Offices within the LOBs conducting UAS work in "stovepipe" fashion
  • DIFFERENCES IN CROPPING SYSTEMS AND SOIL ORGANIC CARBON

    DIFFERENCES IN CROPPING SYSTEMS AND SOIL ORGANIC CARBON

    Before it was used for agriculture and now it is not. 2.Clayey soil Ňeq'e oraque The surface soil can be cultivated but with erosion the soil becomes hard like cement The soil used to be much stronger but it has...