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

Similar documents
C++ does not, as a part of the language, define how data are sent out and read into the program

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

Why Is Repetition Needed?

REPETITION CONTROL STRUCTURE LOGO

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

Chapter 5: Loops and Files

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

CSCE 206: Structured Programming in C++

Increment and the While. Class 15

C++ Input/Output Chapter 4 Topics

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Chapter 4: Control structures. Repetition

do { statements } while (condition);

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Repetition and Loop Statements Chapter 5

Chapter 4: Control structures

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Structured Programming. Flowchart Symbols. Structured Programming. Selection. Sequence. Control Structures ELEC 330 1

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Name Section: M/W T/TH Number Definition Matching (6 Points)

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Loops / Repetition Statements

Unit 7. 'while' Loops

Name Section: M/W T/TH Number Definition Matching (8 Points)

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Scientific Computing

Chapter void Test( int, int, int ); // Function prototype int main() // Function heading { int h; // Local variable

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Chapter 5. Conditions, Logical Expressions, and Selection Control Structures

Chapter 5 Topics. Chapter 5 Topics. Flow of Control. bool Data Type. Flow of Control. Chapter 5

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Quiz Determine the output of the following program:

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

C++ Programming: From Problem Analysis to Program Design, Third Edition

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

In this chapter you will learn:

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

Lecture 7 Tao Wang 1

CSCI 1061U Programming Workshop 2. C++ Basics

Looping. Arizona State University 1

Flow of Control. bool Data Type. Flow Of Control. Expressions. C++ Control Structures < <= > >= ==!= ! &&

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Introduction to Programming

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Exceptions, Case Study-Exception handling in C++.

Flow of programming execution control is sequential unless a control structure is used to change that there are 2 general types of

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

Simple File I/O.

C++ Programming: From Problem Analysis to Program Design, Third Edition

Loops and Files. of do-while loop

Problem Solving With Loops

Chapter 3. More Flow of Control

Principles of Computer Science I

Lab Instructor : Jean Lai

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

An Introduction to Programming with C++ Sixth Edition. Chapter 7 The Repetition Structure

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Lab 10: Alternate Controls

Name SECTION: 12:45 2:20. True or False (12 Points)

CSCE Practice Midterm. Data Types

Problem Solving: Storyboards for User Interaction

STUDENT LESSON A12 Iterations

Lecture # 6. Repetition. Review. If Else Statements Comparison Operators Boolean Expressions Nested Ifs. Switch Statements.

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Computer Programming I - Unit 5 Lecture page 1 of 14

C++ Final Exam 2017/2018

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

CIS 130 Exam #2 Review Suggestions

CPE 112 Spring 2015 Exam III (100 pts) April 8, True or False (12 Points)

CS 103 Lecture 3 Slides

causing a set of statements (the body) to be executed repeatedly. C++ provides three control structures to support iteration (or looping).

What we will learn about this week:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

READ THIS NOW! Failure to read and follow the instructions below may result in severe penalties. Do not start the test until instructed to do so!

CS1004: Intro to CS in Java, Spring 2005

EP241 Computing Programming

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

Study Guide for Test 2

1 Unit 8 'for' Loops

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Compiling C++ Programs Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

CSI33 Data Structures

Transcription:

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 2

Chapter 6 Topics Using a While Statement for Summing and Counting Nested While Loops Loop Testing and Debugging 3

Loops What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly 4

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 5

While Statement SYNTAX 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 LOOP FALSE Expression TRUE body statement 7

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 8

Count-Controlled Loop Example int count; // Loop-control variable count = 4; variable // Initialize loop while(count > 0) // Test expression { cout << count << endl; // Repeated action } count --; // Update loop variable 9

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Example myinfile contains 100 blood pressures Use a while loop to read the 100 blood pressures and find their total 26

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

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

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

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

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 31

// Sentinel controlled loop total = 0; cout << Enter a blood pressure(-1 to stop) ; cin >> thisbp; 32

// Sentinel controlled loop, cont... while(thisbp!= -1) sentinel { } total = total + thisbp; cout << Enter a blood pressure(-1 to stop) ; cin >> thisbp; cout << total; // While not 33

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 34

// End-of-file controlled loop total = 0; myinfile >> thisbp; // Priming read 35

// End-of-file controlled loop, cont... while(cin) // While last read successful { } total = total + thisbp; cout << Enter blood pressure ; cin >> thisbp; another cout << total; // Read 36

// End-of-file at keyboard total = 0; cout << Enter blood pressure << (Ctrl-Z to stop) ; cin >> thisbp; // Priming read 37

// End-of-file at keyboard, cont... while(cin) // While last read successful { } total = total + thisbp; cout << Enter blood pressure ; cin >> thisbp; another cout << total; // Read 38

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 39

Example of Flag-controlled Loop countgoodreadings = 0; issafe = true; // Initialize Boolean flag while(issafe) { cin >> thisbp; if (thisbp >= 200) issafe = false; // Change flag value 40

Example, continued else } countgoodreadings++; cout << countgoodreadings << endl; 41

Common Loop Uses Count all data values Count special data values Sum data values Keep track of current and previous values 42

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 43

Keeping Track of Values (x!= 3) { cout << endl; } FILE CONTENTS previous current count ( x 0 x 0! 0! = 1 = 1 3 1 3 ) 1 44 44

Loop Program Keeping Track of Current and Previous Values int count; char previous; char current; count = 0; infile.get(previous); reads infile.get(current); // Priming 45

Keeping Track of Current and Previous Values, continued while(infile) { } if((current == = ) && (previous ==! )) count++; previous = current; // Update infile.get(current); another // Read 46

Nested Loops initialize outer loop while (outer loop condition) {... } initialize inner loop while(inner loop condition) { inner loop processing and update }... 47 47

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 5 180 140 150 170 120 2318 2 170 210 5232 3 150 151 151 48

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

Algorithm Initialize patientcount to 0 Read first ID and howmany from file 50

Algorithim, cont... 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 51

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 52

Designed Nested Loop Example #include <iostream> #include <fstream> using namespace std; 53

Designed Nested Loop Example int main() { int patientcount; // Declarations int thisid; int howmany; int thisbp; int totalforpatient; int count; float average; ifstream myinfile; 54

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; 55

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; 56

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 << Program terminated. << endl; return 0; 57

Information About 20 Books in Diskfile Price of book myin.dat 3.98 P <eoln> 7.41 H <eoln> 8.79 P <eoln>... Hardback or Paperback? Write a program to find total value of all books 58

C++ Program #include <iostream> #include <fstream> I/O // Access cout // Access file using namespace std; int main(void) { float price; // Declarations char kind; ifstream myinfile; float total = 0.0; int count = 1; 59

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

Trace of Program Variables count price kind total 0.0 1 3.98 P 3.98 2 7.41 H 11.39 3 8.79 P 20.18 4 etc. 20 21 so loop terminates 61

Complexity Complexity is a measure of the amount of work involved in executing an algorithm relative to the size of the problem 62

Polynomial Times N N 0 N 1 N 2 N 3 constant linear 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 63

Loop Testing and Debugging Test data should test all sections of program Beware of infinite loops -- program doesn t stop Check loop termination condition, and watch for off-by-1 bugs(obobs) Use get function for loops controlled by detection of \n character 64

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 65