C++ An Introduction to Computing, 3rd ed. 1 Repetition Chapter 7.

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.
Chapter 4 Repetitive Execution. 2 Types of Repetition There are two basic types of repetition: 1) Repetition controlled by a counter; The body of the.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops and Files.
Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
Chapter 5: Control Structures II (Repetition)
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Chapter 5: Control Structures II (Repetition)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
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 C++ Loop Statements Repetition Revisited. 2 Problem Using OCD, design and implement a function that, given a menu, its first valid choice, and its last.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Controlling Function Behavior Sequence, Selection and Repetition.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 5: Control Structures II (Repetition)
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Selection Chapter 6. C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on introduction to structures Examine if statement in more detail Study.
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.
1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)
Overview Go over parts of quiz? Another iteration structure for loop.
Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions.
Repetition Repeating the Execution of Statements.
C++ Loop Statements Repetition Revisited. Problem Using OCD, design and implement a function that, given a menu, its first valid choice, and its last.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
1 Controlling Behavior Chap.5 Study Sections 5.1 – 5.3 The if and for Statements.
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.
Calvin College Controlling Behavior The if, switch and for Statements.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Control Structures 1 The if, for, and while Statements §5.1, §5.4, & §5.5 (Several examples here; also Lab #4)
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Controlling Behavior The if and for Statements. Function Behavior The behavior of a function is determined by the statements within the function. Statements.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Introduction to Computer Programming
Controlling Behavior The if and for Statements.
Topic 4: Looping Statements
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
while Repetition Structure
Chapter 5: Control Structures II (Repetition)
More Repetition Chap. 8 (Read § ) 1.
Control Structures II (Repetition)
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Alternate Version of STARTING OUT WITH C++ 4th Edition
Let’s all Repeat Together
Chapter 5: Control Structures II (Repetition)
Controlling Behavior The if and for Statements.
Presentation transcript:

C++ An Introduction to Computing, 3rd ed. 1 Repetition Chapter 7

C++ An Introduction to Computing, 3rd ed. 2 Objectives Expand on intro to repetition structures Examine for loops Study while and do loops Look at various kinds of input loops Consider how to choose best loop for a situation First look at algorithm analysis Introduce code reusability via inheritance

C++ An Introduction to Computing, 3rd ed. 3 Intro Example: Punishment of Gauss Summation problem: For punishment in grade school, Gauss was required to sum numbers 1 – 100. He came up with answer (5050) very quickly. (He did not use a repetition algorithm.) We will use repetition in a function to sum the values of 1 through any number, n. Description Software Objects TypeKindMovementName limit value, n integer varyingreceived (in) n … + n integer varyingreturned (out)

C++ An Introduction to Computing, 3rd ed. 4 Steps Required Procedure will require: 1. Initialize a running total to 0 2. Initialize a count to 1 3. Loop through: Add count to the running total Add 1 to count Additional objects now seen: Description Software Objects TypeKindMovementName limit value, n integer varyingreceived (in) n … + n integer varyingreturned (out) runningTotal A counter integer varying count

C++ An Introduction to Computing, 3rd ed. 5 Operations i. Receive an integer ( n ) ii. Initialize integers, runningTotal = 0, count = 1 iii. Add two integers, count and runningTotal, store result iv. Repeat step iii, for each value of count = 1 through n v. Return the integer ( runningTotal )

C++ An Introduction to Computing, 3rd ed. 6 Algorithm, Coding, Testing Algorithm for summation: 1. Initialize runningTotal to 0 2. For each value of count in range 1 through n Add count to runningTotal 3. Return runningTotal View function source code, Figure 7.1Figure 7.1 Driver program, Figure 7.2Figure 7.2 Sample runs of Figure 7.2Figure 7.2 Note use of for loop to do step 2 of the algorithm

C++ An Introduction to Computing, 3rd ed. 7 The for Loop Counter-controlled loops A set of statements executed once for each value in a specified range

C++ An Introduction to Computing, 3rd ed. 8 A Counting Loop The for loop most commonly used to count From one value first To another value last: for (int count = first; count <= last; count++) Statement count = first count <= last Statement count++ F T

C++ An Introduction to Computing, 3rd ed. 9 The for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement for (InitializerExpr; LoopCondition; IncrementExpr) Statement When LoopCondition becomes false, Control proceeds to the next statement. InitializerExpr LoopCondition Statement IncrementExpr F T Note: if the LoopCondition is initially false, then the body of the loop will not be executed even once.

C++ An Introduction to Computing, 3rd ed. 10 Nested Loops Consider the statement in a for loop It can be any kind of statement Including another for statement count = first count <= last Statement count++ F T count = first count <= last Statement count++ F T

C++ An Introduction to Computing, 3rd ed. 11 Nested Loops Loops can be nested: for (int val1 = 1; val1 <= limit1; val1++) for (int val2 = 1; val2 <= limit2; val2++) cout << val1 << ‘*’ val2 “ = “ << val1 * val2 << endl; Output (suppose limit1 == 2, limit2 == 3): 1*1 = 1 1*2 = 2 1*3 = 3 2*1 = 2 2*2 = 4 2*3 = 6 See also Figure 7.3Figure 7.3 And the sample runsample run See also Figure 7.3Figure 7.3 And the sample runsample run

C++ An Introduction to Computing, 3rd ed. 12 Noncounting Loops One of the quirks of the C++ for loop Its three expressions can be omitted: for (;;) { StatementList } for (;;) { StatementList } Such a loop will execute infinitely many times … Unless statements within StatementList permit execution to leave the loop.

C++ An Introduction to Computing, 3rd ed. 13 Noncounting Loops This is the forever loop a for loop without expressions: for (;;) { StatementList 1 if (Expression) break; StatementList 2 } StatementList 1 Expression F T StatementList 2 Repetition continues so long as Expression is false!

C++ An Introduction to Computing, 3rd ed. 14 Pretest Loops If StatementList 1 is omitted from forever loop – results in A test-at-the-top or pretest loop: for (;;) { if (Expression) break; StatementList 2 } Expression F T StatementList 2 StatementList 1

C++ An Introduction to Computing, 3rd ed. 15 The while Loop For such situations, C++ provides the more readable while loop, pattern is: while (Expression) Statement Expression T F Statement Statement can be either a single or compound C++ statement. Repetition continues so long as Expression is true!

C++ An Introduction to Computing, 3rd ed. 16 Example: Bouncing Ball Problem When a ball is dropped, it bounces to ½ of its previous height. We seek a program which simulates this Display number of each bounce and height Repeat until bounce height is very small Description Software Objects TypeKindName current height real varying height bounce number integer varying bounce some small number real constant SMALL_NUMBER Objects

C++ An Introduction to Computing, 3rd ed. 17 Operations i. Input a real value, the original height ii. Initialize bounce to zero iii. Divide height by 2 for rebound height iv. Increment bounce v. Display current bounce number, height vi. Repeat iii – v as long as height ≥ SMALL_NUMBER

C++ An Introduction to Computing, 3rd ed. 18 Algorithm 1. Initialize bounce 0 2. Prompt for, read value for height 3. Display original height value with label 4. Loop: a. If height < SMALL_NUMBER, terminate b. Replace height with height / 2 c. Add 1 to bounce d. Display bounce and he i ght 5. End loop

C++ An Introduction to Computing, 3rd ed. 19 Coding and Testing Note use of while loop, Figure 7.4Figure 7.4 Instead of a pretest forever for loop Note sample runsample run

C++ An Introduction to Computing, 3rd ed. 20 Post-test Loops If StatementList 2 is omitted in a forever loop – results in a test-at-the-bottom or post-test loop: for (;;) { StatementList 1 if (Expression) break; } Expression FT StatementList 1 StatementList 2

C++ An Introduction to Computing, 3rd ed. 21 The do Loop For such situations, C++ provides the more readable do loop, Pattern do Statement while (Expression); Statement can be either a single or compound C++ statement. Repetition continues so long as Expression is true! Expression TF Statement

C++ An Introduction to Computing, 3rd ed. 22 Example: Counting Digits Humans looking at a number can easily count digits Computers must do more than "scan and count" We seek a function which Receives an integer value from the caller Counts digits in the integer Returns the count to the caller

C++ An Introduction to Computing, 3rd ed. 23 Objects and Operations Operations: i. Integer division ( intValue / 10 ) ii. Integer addition (add 1 to numDigits ) iii. Repetition of i and ii as long as intValue is not 0 Description Software Objects TypeKindMovementName an integer value int varyingreceived intValue number of digits in the integer value int varyingreturned numDigits

C++ An Introduction to Computing, 3rd ed. 24 Algorithm 1. Initialize numDigits to 0 2. Loop a. Increment numDigits b. Divide intValue by 10, store result in intValue c. If intValue is 0, terminate repetition 3. Return numDigits Note – we could use a forever for loop for ( ; ; ) { numDigits++; intValue /= 0; if (intValue == 0) break; }

C++ An Introduction to Computing, 3rd ed. 25 Coding and Testing Note that the source code, Figure 7.5 uses a do loop instead Figure 7.5 Observe the driver program, Figure 7.6 Figure 7.6 Sample Runs

C++ An Introduction to Computing, 3rd ed. 26 Input Loops The forever loop is ideal for Reading a list of values Where the end is marked by a sentinel (i.e., an invalid value). Pattern for (;;) { Prompt for value Read value if (value is the sentinel) break; Process value } for (;;) { Prompt for value Read value if (value is the sentinel) break; Process value }

C++ An Introduction to Computing, 3rd ed. 27 Example double ReadAndAverage() { double score, sum = 0.0; int count = 0; for (;;) { cout << “Enter a test score (-1 to quit): “; cin >> score; if (score < 0) break; // test for sentinel count++; sum += score; } if (count > 0) return sum / count; else { cerr << “\n* no scores to average!\n” << endl; exit(1); } Read and average a list of test scores: Forever loop

C++ An Introduction to Computing, 3rd ed. 28 Use of while Loop See also program to process collection of failure times and find mean time to failure. Figure 7.7 Sample Run Note: the forever loop in Figure 7.7 could have been a while loop cout > failureTime; while (failureTime >= 0) { failureTimeSum += failureTime; numComponents++; cout > failureTime; }

C++ An Introduction to Computing, 3rd ed. 29 End-of-File as Sentinel Value Recall that cin is an object of type istream Status flag values can be accessed The eof flag value can be used as a sentinel Forever for loop used in Figure 7.8 for ( ; ; ) { cin.get(ch); if (cin.eof()) break; cout > int (ch) << endl; }Figure 7.8

C++ An Introduction to Computing, 3rd ed. 30 End-of-File as Sentinel Value Problems Platform independence in using the eof as a flag Results of the good flag being set – if stream is cleared, possible to read after eof mark! Note program in Figure 7.9 which illustrates thisFigure 7.9

C++ An Introduction to Computing, 3rd ed. 31 Input Loops The Counting Approach Consider a program which prompts for, receives as input the number of incoming items Then design the for loop to count that many items Note such a for loop in Figure 7.10Figure 7.10

C++ An Introduction to Computing, 3rd ed. 32 Input Loops The Counting Approach Problem Number of incoming data items may be difficult to determine Possible to query user before/after each iteration Note use of do loop in this approach, Figure 7.11Figure 7.11 Also possible to create a bool function to do the query Call the query function in the while( condition)

C++ An Introduction to Computing, 3rd ed. 33 Choosing a Loop Use the for loop for counting problems. Design algorithms for non-counting problems using a general Loop statement, and see where it is appropriate for repetition to terminate: If at the loop’s beginning, use the while loop If at its end, use the do loop If in its middle, use the forever loop.

C++ An Introduction to Computing, 3rd ed. 34 Intro to Algorithm Analysis Consider once again, Gauss's quick solution (not using repetition) … Sum of numbers 1 … 5

C++ An Introduction to Computing, 3rd ed. 35 Intro to Algorithm Analysis So in general: Thus possible to write a non looping version of our sum function int sum (int n) { return n * (n + 1) / 2; } A better algorithm Takes many less operations

C++ An Introduction to Computing, 3rd ed. 36 OBJECTive Thinking: Code Reuse through Inheritance Consider our Name class What if we need a class which also requires titles

C++ An Introduction to Computing, 3rd ed. 37 Inheritance When a new class is a specialization of an existing class We use the C++ inheritance mechanism It drives the new class from the existing class Illustration #include "Name.h" class TitledName : public Name { // attributes and operations };

C++ An Introduction to Computing, 3rd ed. 38 Inheritance TitleName class derived from Name Figure 7.13 Driver program with sample run, Figure 7.14 Figure 7.14

C++ An Introduction to Computing, 3rd ed. 39 Inheritance Public variables and methods from parent class available to child class objects

C++ An Introduction to Computing, 3rd ed. 40 Inheritance Note from TitledName definitions: Constructors and initialization Accessor and mutator methods I/O methods General Principle: Constructors and methods of a class should only access instance variables defined within the same class. Inherited instance variables should be accessed through inherited constructors or methods

C++ An Introduction to Computing, 3rd ed. 41 Object Oriented Design Identify objects in problem Build class to represent if needed As needed use inheritance to consolidate common attributes, operations Identify operations in problem If operation not predefined, write function to perform that operation As appropriate identify class which should provide the operation, define operation as a method Organize objects, operations into algorithm that solves your problem