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

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

Why Is Repetition Needed?

REPETITION CONTROL STRUCTURE LOGO

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

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

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

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

Increment and the While. Class 15

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

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

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

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

Chapter 2: Overview of C++

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

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

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

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

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.

do { statements } while (condition);

Chapter 3 Problem Solving and the Computer

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

Linked List using a Sentinel

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

Computer Programming : C++

Chapter 5: Control Structures II (Repetition)

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

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

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

CSI33 Data Structures

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

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

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!

Introduction to Programming

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

(of an identifier) the range of program statements within which the identifier is recognized as a valid name

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay

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

Chapter 2: Basic Elements of C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2. C++ Basics

Unit 7. 'while' Loops

READ THIS NOW! Do not start the test until instructed to do so!

BITG 1233: Introduction to C++

2 nd Week Lecture Notes

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

In this chapter you will learn:

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

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

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

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

COP 2000 Note Framework Chapter 5 - Repetition Page 1

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

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

C/C++ Programming Lecture 7 Name:

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

Introduction to Programming EC-105. Lecture 2

The American University in Cairo Computer Science & Engineering Department CSCE Dr. KHALIL Exam II Spring 2010

Looping. Arizona State University 1

Objectives. In this chapter, you will:

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

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

Chapter 3. More Flow of Control

while Loops Lecture 13 Sections Robb T. Koether Wed, Sep 26, 2018 Hampden-Sydney College

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Programming. C++ Basics

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Chapter 8 Statement-Level Control Structure

Ch 6. Functions. Example: function calls function

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

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

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

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

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Introduction to C++ (Extensions to C)

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

CHAPTER 3 BASIC INSTRUCTION OF C++

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

C++ Final Exam 2017/2018

Add Subtract Multiply Divide

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

CS2141 Software Development using C/C++ C++ Basics

Lab 10: Alternate Controls

Chapter 2 Basic Elements of C++

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS240 BRANCHING STATEMENTS

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

CS 1044 Programming in C++ Test 1 READ THIS NOW! Failure to read and follow the instructions below may result in severe penalties.

Fundamentals of Programming CS-110. Lecture 2

Programming Language. Functions. Eng. Anis Nazer First Semester

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

LECTURE 02 INTRODUCTION TO C++

Chapter 7. Additional Control Structures

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Chapter 4 - Notes Control Structures I (Selection)

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

CS101 PLEDGED SPRING 2001

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

Transcription:

Iteration Iteration causing a set of statements (the body) to be executed repeatedly. 1 C++ provides three control structures to support iteration (or looping). Before considering specifics we define some general terms that apply to any iteration construct: pass (or iteration) - one complete execution of the body loop entry - the point where flow of control passes to the body loop test - the point at which the decision is made to (re)enter the body, or not loop exit - the point at which the iteration ends and control passes to the next statement after the loop termination condition - the condition that causes the iteration to stop When designing a loop, it is important to clearly identify each of these. Understanding the termination condition, and what guarantees it will eventually occur, are particularly vital.

while Loop 2 The most versatile loop construct in C++ is the while statement. Syntactically: while <bool expr> <loop body> The Boolean expression must be enclosed in parentheses, and <loop body> can be either a single statement or a compound statement. Semantically: while false <bool expr> true <loop body> The Boolean expression is examined before each pass through the body of the loop. If the Boolean expression is true, the loop body is executed; if it is false, execution proceeds to the first statement after the loop body..

while Loop Example 3 Example: #include <iostream> using namespace std; int main() { const char ASTERISK = '*'; // 1 int numast; // 2 int numprinted = 0; // 3 cout << "How many asterisks do you want? "; // 4 cin >> numast; // 5 while (numprinted < numast) { // 6 cout << ASTERISK; // 7 numprinted++; // 8 cout << endl; // 9 return 0; // 10 This is a count-controlled loop. The loop control variable (LCV) is a variable whose value determines whether the loop body is executed.

while Loop Characteristics 4 Some observations: - It is possible that the body of the loop will never be executed. - It is possible that the loop test condition will become false in the middle of an iteration. Even so, the remainder of the loop body will be executed before the loop test is performed and iteration stops. - The loop test must involve at least one variable whose value is (potentially) changed by at least one statement within the loop body. Why? while (numprinted < numast) { // 6 cout << ASTERISK; // 7 numprinted++; // 8 cout << endl; // 9

Count Controlled Loop 5 Count Controlled Loop a loop that terminates when a counter reaches some limiting value The LCV (loop control variable) will be: - an integer variable used in the Boolean expression - initialized before the loop, - incremented or decremented within the loop body cout << "How many asterisks do you want? "; // 4 cin >> numast; // 5 // modified implementation while ( numast > 0 ) { // 6 cout << ASTERISK; // 7 numast--; // 8 cout << endl; // 9

Event Controlled Loop 6 Event Controlled Loop: loop that executes until a specified situation arises to signal the end of the iteration. const int CENTSPERDOLLAR = 100; // 1 string Description; // 2 int Dollars, // 3 Cents; // 4 int totalcents = 0; // 5 Visual C++ 46.50 Excedrin 2.99 Excedrin Migraine 3.99 How to Solve It 33.95 The Art of War 17.50 getline(in, Description, '\t'); // 6 In >> Dollars; // 7 In.ignore(1, '.'); // 8 In >> Cents; // 8 In.ignore(INT_MAX, '\n'); // 10 while ( In ) { // 11 totalcents = totalcents + + CENTSPERDOLLAR*Dollars + Cents; // 12 This loop is terminated by the event of an input failure. // repeat lines 6 through 10

Sentinel Controlled Loop 7 Sentinel loop: loop that terminates when a specified marker (dummy data value) is read, signaling the end of the iteration. Here we modify the previous input file to include a special marker line to signify the end of the price data in the file: const int CENTSPERDOLLAR = 100; // 1 const string SENTINEL = "xxxnoitemxxx"; // 2 getline(in, Description, '\t'); // 7 In >> Dollars; // 8 In.ignore(1, '.'); // 9 In >> Cents; // 10 In.ignore(INT_MAX, '\n'); // 11 while ( Description!= SENTINEL ) { // 12 totalcents = totalcents + + CENTSPERDOLLAR*Dollars + Cents; // 13 // repeat lines 7 through 11 Visual C++ 46.50 Excedrin 2.99 Excedrin Migraine 3.99 How to Solve It 33.95 The Art of War 17.50 xxxnoitemxxx 0.00 Deliver to: Joe Bob Hokie 666 Pritchard Hall This loop is terminated by the event of reading the special sentinel value.

An Improvement Using Hybrid Control 8 The pure sentinel control on the previous slide is risky. What would happen if the sentinel line were omitted? We can eliminate this problem by adding a check for input failure to the loop test: const int CENTSPERDOLLAR = 100; // 1 const string SENTINEL = " xxxnoitemxxx "; // 2 getline(in, Description, '\t'); // 7 In >> Dollars; // 8 In.ignore(1, '.'); // 9 In >> Cents; // 10 In.ignore(INT_MAX, '\n'); // 11 while ( In && Description!= SENTINEL ) { // 12 totalcents = totalcents + + CENTSPERDOLLAR*Dollars + Cents; // 13 // repeat lines 7 through 11 Visual C++ 46.50 Excedrin 2.99 Excedrin Migraine 3.99 How to Solve It 33.95 The Art of War 17.50 xxxnoitemxxx 0.00 This loop is terminated by either the event of an input failure, or by the event of reading the special sentinel value.

Boolean Loop Control Variable 9 It's fairly common to use a Boolean variable to record the results of a more complicated test. Here we assume that there is a sentinel line in which the price is invalid: getline(in, Description, '\t'); // 6 In >> Dollars; // 7 In.ignore(1, '.'); // 8 In >> Cents; // 9 In.ignore(INT_MAX, '\n'); // 10 bool priceok = (Dollars > 0) (Dollars == 0 && Cents > 0); // 11 while ( In && priceok ) { // 12 totalcents = totalcents + + CENTSPERDOLLAR*Dollars + Cents; // 13 // repeat lines 6 through 10 priceok = (Dollars > 0) (Dollars == 0 && Cents > 0); // 19 Visual C++ 46.50 Excedrin 2.99 Excedrin Migraine 3.99 How to Solve It 33.95 The Art of War 17.50 xxxnoitemxxx 0.00 Note that the Boolean loop control variable priceok could be replaced by the condition used to set it, but the resulting code would perhaps not be as readable.