Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Chapter 5: Loops and Files.
Objectives You should be able to describe:
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
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.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Loops and Files. 5.1 The Increment and Decrement Operators.
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.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: The while Statement cin within a while Loop The for.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5 Repetition. 2 Objectives You should be able to describe: The while Statement cin within a while Loop The for Statement The do Statement Common.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
Topic 4: Looping Statements
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Unit 3 Lesson 9 Repetition Statements (Loops)
Chapter 5: Control Structures II (Repetition)
CHAPTER 6: REPETITION AND LOOP STATEMENTS
Loop Structures.
Lecture 4 - Loops UniMAP EKT120 Sem 1 08/09.
Control Structures II (Repetition)
Chapter 5: Loops and Files.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
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.
Topics Introduction to Repetition Structures
Chapter 5: Looping Starting Out with C++ Early Objects Eighth Edition
Control Structures - Repetition
Chapter 8 Repetition Statements
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Alternate Version of STARTING OUT WITH C++ 4th Edition
Chapter 6: Repetition Structures
Chapter 5: Repetition Structures
Iteration: Beyond the Basic PERFORM
Chapter 6: Repetition Statements
Computing Fundamentals
Alternate Version of STARTING OUT WITH C++ 4th Edition
Chapter 5: Control Structures II (Repetition)
Objectives You should be able to describe: The while Statement
Topics Introduction to Repetition Structures
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
ICS103: Programming in C 5: Repetition and Loop Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Revised 2015 E.L. Jones, Ph.D., FAMU

Topics 5.1 The Increment and Decrement Operators 5.2 Introduction to Loops: The while Loop 5.3 Using the while loop for Input Validation 5.4 Counters 5.5 The do-while loop 5.6 The for loop 5.7 Keeping a Running Total

Topics (continued) 5.8 Sentinels 5.9 Using a Loop to Read Data From a File 5.10 Deciding Which Loop to Use 5.11 Nested Loops 5.12 Breaking Out of a Loop 5.13 The continue Statement 5.14 Creating Good Test Data

Chapter 5 Repetition / Loops Increment/Decrement STOP / START HERE Chapter 5 Repetition / Loops Increment/Decrement See pr8-09.cpp

A. Some New Operators Increment and Decrement ++ adds one to a variable val++; is the same as val = val + 1; -- subtracts one from a variable val--; is the same as val = val – 1; can be used in prefix mode (before) or postfix mode (after) a variable See pr5-01.cpp

Prefix Mode ++val and --val increment/decrement the variable, then return the new value of the variable. * int k = 3, m = 5; cout << k << “ “ << ++k << “ “ << k << endl; cout << m << “ “ << --m << “ “ << --m << endl; The new value of the variable is available from that point in the expression/statement.

Prefix Mode Example int x = 1, y = 1; x = ++y; // y is incremented to 2 // Then 2 is assigned to x cout << x << " " << y; // Displays 2 2 x = --y; // y is decremented to 1 // Then 1 is assigned to x << " " << y; // Displays 1 1

Postfix Mode val++ and val-- return the old value of the variable, then increment or decrement the variable * int k = 3, m = 5; cout << k++ << “ “ << k << “ “ << ++k << endl; cout << m-- << “ “ << m << “ “ << --m << endl; The old value of the variable is returned … and The new value of the variable is available beyond this point in the expression/statement.

Postfix Mode Example x = y++; // y++ returns a 1 cout << x int x = 1, y = 1; x = y++; // y++ returns a 1 // The 1 is assigned to x // and y is incremented to 2 cout << x << " " << y; // Displays 1 2 x = y--; // y-- returns a 2 // The 2 is assigned to x // and y is decremented to 1 << " " << y; // Displays 2 1 See pr5-02.cpp

Increment & Decrement Notes These operators CHANGE the value of a variable The operand must be a variable Can be used in arithmetic expressions result = num1++ + --num2; result = (num1 + num2)++; //Illegal.WHY? Can be used in relational expressions if (++num > limit) // Comparisons are if (num++ > limit) // different.

(based on counting / sequence) STOP / START HERE Chapter 5 Repetition / Loops for Loop (based on counting / sequence) See pr8-09.cpp

Chapter 5 – LOOPING Repetition STOP / START HERE Chapter 5 – LOOPING Repetition See pr8-09.cpp

B. The for Loop Loop based on counting Example: int count; for (count = 1; count <= 10; count++) cout << count << “ “; cout << endl; Output: 1 2 3 4 5 6 7 8 9 10 What about: for ( count = 5; count <= 40; count+=5 )

Syntax / Format { body; } for(initialization; continuation_test; update) { body; } No ; goes here

for Loop Mechanics

for Loop Flow of Control true statement(s) false test initialization code update code

for Loop Example (Tracing) int sum = 0, num; for (num = 1; num <= 6; num++) sum += num; cout << "Sum of 1–6 is “ << sum << endl; Step - 1 2 3 4 5 6 7 num (before) ? condition T F sum 10 15 21 num (after) See pr5-09.cpp

for Loop Notes If contination_condition is false the first time it is evaluated, the body of the loop will not be executed The update expression can modify the control variable by any amount (commonly ++, --, +=, -=, *=, /=, %= ) The loop control variable should not be modified in the body of the loop.

for Loop Modifications Can define variables in initialization code Their scope is the for loop Initialization and update code can contain more than one statement Separate statements with commas, not semicolons Example: for (int sum = 0, num = 1; num <= 10; num++) sum += num;

(indefinite repetition) STOP / START HERE Chapter 5 Repetition / Loops part 3 - while Loop (indefinite repetition) See pr8-09.cpp

while Loop Flow of Control false condition true statement(s)

How the while Loop Works while (condition) { loop_body } condition is evaluated if it is true, the body is executed, and then condition is evaluated again if it is false, the loop is exited

while Loop Example Execution Trace int val = 5; while (val >= 0) { cout << val << " "; val--; } produces output: 5 4 3 2 1 0 Execution Trace Step 1 2 3 4 5 6 7 val (before) -1 condition T F output val (after) See pr5-03.cpp

The while Loop Programming construct to execute certain statements repeatedly (>= 0 times) while loop format: while (condition) { loop_body statement(s); } The {} can be omitted if there is only one statement in the body of the loop

while Loop is a Pretest Loop while is a pretest loop (condition is evaluated before the loop executes) If the condition is initially false, the statement(s) in the body of the loop are never executed If the condition is initially true, the statement(s) in the body continue to be executed until the condition eventually becomes false

Exiting (terminating) the Loop The loop body must contain code to force the condition to eventually become false, so the loop can be exited Otherwise, you have an infinite loop (i.e., a loop that does not stop) Example of an infinite loop: x = 5; while (x > 0) // Infinite loop: NOTHING cout << x; // x NOT CHANGED from 5.

Common Loop Errors Don’t forget the { } : int numEntries = 1; while (numEntries <=3) cout << "Still working … "; numEntries++; // not in the loop body Don’t use = when you mean to use == while (numEntries = 3) // always true { cout << "working … "; numEntries++; } while (numEntries = 0) // always false { … }

Constructing Continuation Condition from Stopping Condition Continuation Condition = NOT stopping X > 5 X <= 5 [ (NOT X>5) ] X <= 5 X > 5 [ (NOT X<= 5) ] X != 4 X == 4 X>5 or Y == 2 X<=5 && Y!=2 [ NOT (X>5) and NOT (Y==2) ] M outside (1,9] M>1 && M<=9 [ Inside (1,9] ] Q inside [5,18) Q<5 || Q>=18 [ Outside [5,18) ] Failed cin operation ! cin.fail() [ non-failure ] Failed read into variables a,b,c from stream inF (inF >> a >> b >> c) [Successful read] x is odd and y is even x is even or y is odd (x % 2 == 0) || (y%2 ==1)

(repetition patterns) STOP / START HERE Chapter 5 Repetition / Loops part 4 - while Loop (repetition patterns) See pr8-09.cpp

Repetition Pattern: READ-CHECK-USE Data-Driven Goal: Read and process input till end of data. Input design: List of values that ends with a special value called a SENTINEL that represents “END OF DATA”. Sample Problem: Read and display input values. Input design: input values terminated by -999. Inputs: 5 9 4 8 7 -999 Expected Outputs: 5 9 4 8 7

Repetition Pattern: READ-CHECK-USE ALGORITHM: Read num. // READ. if (num is not SENTINEL) // CHECK. process num. // USE. Read num. if (num is not SENTINEL) process num ...

Repetition Pattern: READ-CHECK-USE ALGORITHM implemented as while loop: cin >> num; // READ. while (num != -999) // CHECK. { cout << num << “ “; // USE. cin >> num; // READ. } . . . // Rest of program. Pattern: R-C-U R-C-U … R-C

Repetition Pattern: READ-CHECK-USE Input File-Driven Goal: Read and process input file till end of data. Input design: No special values in file. Sample Problem: Read and display values in file. Input file contains: 5 9 4 8 7 Expected Outputs: 5 9 4 8 7

Repetition Pattern: READ-CHECK-USE (input file) ALGORITHM: Read num. // READ. if (read successful) // CHECK. process num. // USE. Read num. if (read successful) process num ...

Repetition Pattern: READ-CHECK-USE (input file) ALGORITHM implemented as while loop: ifstream inF(“filename”); while ( inF >> num ) // READ + CHECK. { cout << num << “ “; // USE. } . . . // Rest of program. Pattern: R-C-U R-C-U … R-C

Repetition Pattern: READ-CHECK-USE (input file – eof() function) ALGORITHM implemented as while loop with eof(): ifstream inF(“filename); inF >> num; // READ. while ( ! inF.eof() ) // CHECK. { cout << num << “ “; // USE. inF >> num; // READ. } . . . // Rest of program. Pattern: R-C-U R-C-U … R-C

Repetition Pattern: CHECK-READ-USE Result-Driven Goal: Sum input values until sum exceeds Limit. Input design: List of input values, no sentinel. Sample Problem: Limit = 17. Inputs: 5 3 7 4 8 7 Expected Outputs: 19

Repetition Pattern: CHECK-READ-USE ALGORITHM: sum = 0 if (sum <= Limit) // CHECK. Read num. // READ Process num. // USE. if (sum <= Limit) Read num. Process num. ...

Repetition Pattern: CHECK-READ-USE ALGORITHM implemented as while loop: int num, Limit, sum = 0; while (sum <= Limit) // CHECK. { cin >> num; // READ. sum += num; // USE. } . . . // Rest of program. Pattern: C-R-U C-R-U … C

Chapter 5 Repetition / Loops part 5 - Loop processing patterns STOP / START HERE Chapter 5 Repetition / Loops part 5 - Loop processing patterns See pr8-09.cpp

Enabling the User to Control Repetition (A) User can specify the sentinel value marking the end of inputs. (B) User can specify number of input values. The control data must be the first input read, prior to reading the data values.

Count Driven Processing Counter: variable that is incremented or decremented each time a loop repeats Can be used to control execution of the loop (loop control variable) Must be initialized before entering loop Must be updated in the loop body or loop header (e.g., for(…) / while(…) ) See pr5-05.cpp

Example: User Controls Repetition (for loop preferred) int num, limit; cout << "How many entries in table? "; cin >> limit; cout << "Table of squares\n"; cout << “number square\n"; for (num=1; num <= limit; num++) { cout << setw(5) << num << setw(6) << num*num << endl; } See pr5-06.cpp

Example: User Controls Repetition (equivalent while loop – not advised) int num, limit; cout << "Table of squares\n"; cout << "How high to go? "; cin >> limit; cout << “number square\n"; num = 1; while (num <= limit) { cout << setw(5) << num << setw(6) << num*num << endl; num++; } See pr5-06.cpp

Desired Result: Accumulators Accumulator: variable that updated each time a loop repeats “answer, so far” Running totals Other running results computed using +=, -=, *=, /= or %= Additive accumulator initialized to 0 Multiplicative accumulators initialized by 1. See pr5-05.cpp

Example: Sum of N Input Values int numValues, count, num, sum; cout << “Enter #values to add: “; cin >> numValues; sum = 0; // Accumulator must begin at 0. for (count=1; count <= numValues; count++) { cin >> num; sum += num; } See pr5-06.cpp

Example: Product of N Input Values int numValues, count, num, product; cout << “Enter #values to multiply: “; cin >> numValues; product = 1; // Accumulator must begin at 1. for (count=1; count <= numValues; count++) { cin >> num; product *= num; } See pr5-06.cpp

Example: Sums of Negative and Positive Input Values int numValues, count, num; int sumPos, sumNeg; // 2 Accumulators. cout << “Enter #input values: “; cin >> numValues; sumPos = sumNeg = 0; // Accum’s begin at 0. for (count=1; count <= numValues; count++) { cin >> num; if (num > 0) sumPos += num; else if (num < 0) sumNeg += num; // WHY? } See pr5-06.cpp

Example: Minimum Input Value Accumulator is … “minimum, so far” int numValues, count, num; int minVal; // Accumulator. cout << “Enter #input values: “; cin >> numValues; //?? Initial value of minVal? Best to use 1st value. cin >> minVal; for (count=2; count <= numValues; count++) { cin >> num; if (num < minVal) minVal = num; } See pr5-06.cpp

Chapter 5 Repetition / Loops part 6 - do-while Loop STOP / START HERE (repeat … test) See pr8-09.cpp

do-while Flow of Control statement(s) condition false true See pr5-07.cpp

The do-while Loop do-while: a post test loop (condition is evaluated after the loop executes) Format: do { loop_body } while (condition); Notice the required ;

do-while Loop Notes Loop always executes at least once Execution continues as long as condition is true; the loop is exited when condition becomes false Two major uses: Input validation Menu-driven programs See pr5-08.cpp

Data Validation Pattern READ-CHECK Rationale: Avoid garbage-in, garbage-out (GIGO) by confirming validity of inputs. Prompt for and read input data. Check the data for validity. If data value is invalid Display error message Goto step 1. Process the input data value. See pr5-04.cpp

Repetition Pattern: READ-CHECK Data-Driven ALGORITHM: Valid means num < 15 (Limit) Read num. // READ. if (num is not valid) // CHECK. Read num. // READ. if (num is not valid) Read num. ... // Use valid value

Validation Pattern: READ-CHECK Validation ALGORITHM implemented as a do-while loop: int num; // Must be < 15. do { cin >> num; // READ. } while (num >= 15); // CHECK (for invalid). . . . // Rest of program. Pattern: R-C R-C … C

Repetition Pattern: READ-CHECK Validation ALGORITHM implemented as while loop (not advised): int num; cin >> num; // READ. while (num >= Limit) // CHECK. { cin >> num; // READ. } . . . // Rest of program. Pattern: R-C R-C … C

Input Validation using the do-while Loop do { cout << "Enter a number (1-100) and" << " I will guess it. "; cin >> number; } while (number < 1 || number > 100);//Invalid. // … Code to use the valid number goes here.

Input Validation: while Loop Example cout << "Enter a number (1-100) and" << " I will guess it. "; cin >> number; while (number < 1 || number > 100)//outside range { cout << "Number must be between 1 and 100." << " Re-enter your number. "; } // … Code to use the valid number goes here.

Menu-Driven Program Suppose menu choice to QUIT is char ‘Q’. PATTERN: do { //-| Display menu and read choice. //-| Perform menu choice. switch (choice) ... }//switch } while (choice != ‘Q’);

(2-dimensional patterns) STOP / START HERE Chapter 5 Repetition / Loops part 7 – Nested loops (2-dimensional patterns) See pr8-09.cpp

5.10 Deciding Which Loop to Use while: pretest loop (Not sure how many repetitions, possibly zero) Patterns: RCU, CU do-while: post test loop (must execute body at least once, e.g., menu-driven) Patterns: RC for: pretest loop (counter or sequence controlled loop)

5.11 Nested Loops A nested loop is a loop inside the body of another loop Example: for (row = 1; row <= 3; row++) { for (col = 1; col <= 3; col++) cout << row * col << endl; } outer loop inner loop See pr5-14.cpp

Notes on Nested Loops Inner loop goes through all its repetitions for each repetition of outer loop Inner loop repetitions complete sooner than outer loop Total number of repetitions for inner loop is product of number of repetitions of the two loops. In previous example, inner loop repeats 9 times

Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Revised 2015 E.L. Jones, Ph.D., FAMU

More for Loop Modifications (These are NOT Recommended) Can omit initialization if already done int sum = 0, num = 1; for (; num <= 10; num++) sum += num; Can omit update if done in loop for (sum = 0, num = 1; num <= 10;) sum += num++; Can omit test – may cause an infinite loop for (sum = 0, num = 1; ; num++) Can omit loop body if all work is done in header

Using read failure to Test for the End of a File instream >> value -- returns false when not successful Example: while (datafile >> score) { sum += score; datafile >> score; } See pr5-12.cpp

Using the eof() Function to Test for the End of a File instream.eof() member function returns true when the previous read encountered the end of file. Example: datafile >> score; while (!datafile.eof()) { sum += score; } See pr5-12.cpp

Problems Using eof() For the eof() function to work correctly using this method, there must be a whitespace (space, tab, or [Enter] ) between the last data value and the EOF marker. InBuffer: 33<ENTER><EOF> 33 is read but ! eof() Otherwise the eof() will be set when reading the final data value; this value will not be processed. when InBuffer: 33<EOF> , 33 is read but eof() true. But after the extraction, the buffer contains only whitespace (but <EOF> is not exposed, so eof() is false, and there appears to be data in InBuffer. InBuffer: <ENTER><EOF>

5.13 The continue Statement Can use continue to go to end of loop body and prepare for next repetition while and do-while loops go to test and repeat the loop if test condition is true for loop goes to update step, then tests, and repeats loop if test condition is true Use sparingly – like break, can make program logic hard to follow See pr5-16.cpp

5.14 Creating Good Test Data Program should work under different conditions normal situations Extreme conditions near the limits of valid inputs invalid input Quality of test data vs quantity Data should force loops/decisions to achieve all possible outcomes File pr5-17.cpp corresponds to program 5-17 on pp. 284-285 in the text. See also file pr5-17B.cpp as a solution to the problems discussed in program 5-17.