Chapter 6 Looping Dale/Weems. 2 Chapter 6 Topics l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition.

Slides:



Advertisements
Similar presentations
Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested.
Advertisements

Computer Science 1620 Loops.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 5, 2005.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
1 Lecture 15 Chapter 6 Looping Dale/Weems/Headington.
Chapter 6 Loops and Files. 2 Knowledge Goals Understand the semantics of while loop Understand when a count-controlled loop is appropriate Understand.
1 Lecture 16 Chapter 6 Looping Dale/Weems/Headington.
Chapter 5: Loops and Files.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
1 Chapter 5 File Objects and Looping Statements. 2 Chapter 9 Topics l Using Data Files for I/O l While Statement Syntax l Count-Controlled Loops l Event-Controlled.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
1 Chapter 6 Looping Dale/Weems/Headington. 2 l Physical order vs. logical order l A loop is a repetition control structure based on a condition. l it.
1 Chapter 5 File Objects and Looping Statements (Some slides have been modified from their original format)
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Chapter 6 Looping.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 6 Looping CS185/09 - Introduction to Programming Caldwell College.
Chapter 6 Looping. 2 Chapter 6 Topics l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition to.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
1 Looping. 2 Chapter 6 Topics  While Statement Syntax  Phases of Loop Execution  Two Types of Loops: Count-Controlled Loops &Event-Controlled Loops.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Control Structures Repetition or Iteration or Looping Part II.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
Overview Go over parts of quiz? Another iteration structure for loop.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Loops and Files. 5.1 The Increment and Decrement Operators.
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Looping ROBERT REVAES. Logical Operators  && AND  Both have to be true for it to evaluate to be true.  || OR  One or the other has to be true for.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Beginning C For Engineers Fall 2005 Lecture 3: While loops, For loops, Nested loops, and Multiple Selection Section 2 – 9/14/05 Section 4 – 9/15/05 Bettina.
1 Programming in C++ Dale/Weems/Headington Chapter 6 Looping.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
1 Looping Chapter 6 2 Getting Looped in C++ Using flags to control a while statement Trapping for valid input Ending a loop with End Of File condition.
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?
Loop. 3.1Introduction to Repetition Structures Loop – a block of code that, under certain conditions will be executed repeatedly. Do Prompt for and input.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Chapter 6 Looping.
Loop Structures.
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Loops A loop is a repetition control structure.
Repetition Control Structure
Let’s all Repeat Together
Repetition Statements (Loops) - 2
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Chapter 6 Looping Dale/Weems

2 Chapter 6 Topics l While Statement Syntax l Count-Controlled Loops l Event-Controlled Loops l Using the End-of-File Condition to Control Input Data l Nested While Loops l Loop Testing and Debugging

3 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

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

5 Count-controlled loops contain n An initialization of the loop control variable n An expression to test if the proper number of repetitions has been completed n An update of the loop control variable to be executed with each iteration of the body Count-Controlled Loops

6 int count; // Loop-control variable 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 Example

7 Types of Event-Controlled Loops l Sentinel controlled Keep processing data until a special value that 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 7

8 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 8

9 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 9

10 A Sentinel-controlled Loop l Requires a “priming read” l A priming read is the reading of one set of data before the loop to initialize the variables in the expression

11 // 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;

12 End-of-File Controlled Loop l 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

13 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

14 // 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;

15 Flag-controlled Loops l 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

16 countGoodReadings = 0; isSafe = true; // Initialize Boolean flag while(isSafe) { cin >> thisBP; if (thisBP >= 200) isSafe = false; // Change flag value else countGoodReadings++; } cout << countGoodReadings << endl;

17 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

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

19 Algorithm Initialize patientCount to 0 Read first ID and howMany from file While not end-of-file Increment patientCount Display ID Read and sum this patient’s BP’s Calculate and display average for patient Read next ID and howMany from file display patientCount

20 Designing Nested Loops 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

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

22 myInfile.open(“BP.dat”); if (!myInfile) // Opening failed { cout > thisID >> howMany; // Priming read 22

23 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 read myInfile >> thisID >> howMany; } 23

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

25 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” bugs(OBOBs) 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