1 Programming in C++ Dale/Weems/Headington Chapter 6 Looping.

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Chapter 5: Control Structures II (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.
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.
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.
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.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Chapter 5: Control Structures II (Repetition)
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
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.
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
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.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
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.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
1 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while.
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.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
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 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.
1 do-while Statement 2 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX.
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 Looping Dale/Weems/Headington. 2 KA/JS/P Warning l Save your work often! l In the Khan Academy, JavaScript environment, infinite loops will lock up.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
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.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Chapter 6. Loops A control structure that causes a statement or group of statements to be executed repeatedly There are 3 types of loops –while –for –do.
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?
Computer Programming -1-
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 Loops and Files
REPETITION CONTROL STRUCTURE
Chapter 6 Looping.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Loops A loop is a repetition control structure.
Repetition Statements (Loops) - 2
Presentation transcript:

1 Programming in C++ Dale/Weems/Headington Chapter 6 Looping

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

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 While Statement SYNTAX while ( Expression ) {.. // loop body. } NOTE: Loop body can be a single statement, a null statement, or a block.

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 expression FALSE TRUE body statement

6 Count-controlled loop contains an intialization 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

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 count so loop terminates Trace and Output OUTPUT: Done

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

10 ifstream myInfile ; int ThisBP ; int Total ; int count ; count = 0 ; // initialize while ( count < 100 ) // test expression { myInfile >> ThisBP ; Total = Total + ThisBP ; count++ ; // update } cout << “The total = “ << Total << endl ;

11 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.

12 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.

13 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.

14 A Sentinel-controlled loop l Requires a “priming read” l “Priming read” means you read one set of data before the while

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

16 End-of-File controlled loop depends on fact that a file goes into fail state when you try to read a data value beyond the end of the file.

17 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

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

19 Flag-controlled loops l You initialize a flag (usually to 1 or 0) 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

20 CountGoodReadings = 0; Safe = 1; // initialize flag to 1 while (Safe) { cin >> ThisBP; if ( ThisBP >= 200 ) Safe = 0; // change flag to 0 else CountGoodReadings++; } cout << CountGoodReadings << endl;

21 Loops often used to l Count all data values l Count special data values l Sum data values l Keep track of previous and current values

22 Previous and current values l Write a program that counts the number of != operators in a program file l Read one character in the file at a time l Keep track of current and previous characters

23 Keeping track of values (x != 3) { cout << endl; } FILE CONTENTS previous current count ( x 0 ! = 1 = ‘ ‘ 1 x ‘ ‘ 0 3 ) 1 ‘ ‘ 3 1 ‘ ‘ ! 0

24 int count; char previous, current; count = 0 ; inFile.get (previous); // priming reads inFile.get(current); while (inFile) { if ( (current == ‘ = ‘) && (previous == ‘!’) ) count++; previous = current;// update inFile.get(current); // read another }

25 Patient Data l A file contains blood pressure data for different people. l 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

27 Algorithm uses Nest of 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

28 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.

#include #include int main (void) { int PatientCount, // declarations ThisID, HowMany, ThisBP, TotalForPatient, Count; float Average; ifstream myInfile;

myInfile.open(“A:\\BP.dat”); if (!myInfile ) // opening failed { cout > ThisID >> HowMany; // priming read

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 << int (Average +.5) << endl; // round myInfile >> ThisID >> HowMany; // another read }

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

33 Information about 20 books in diskfile “A:\\myIn.dat” 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

34 #include // for cout #include // for file I/O int main (void) { float price ; // declarations char kind ; ifstream myInfile ; float total = 0.0 ; int count = 1; Program to read info about 20 books from a disk file

35 Rest of Program myInfile.open(“A:\\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 ; }

36 Trace of Program Variables count price kind total ‘P’ ‘H’ ‘P’ etc so loop terminates