Download presentation
Presentation is loading. Please wait.
Published byMartin Caldwell Modified over 8 years ago
1
C++ An Introduction to Computing, 3rd ed. 1 Repetition Chapter 7
2
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
3
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 1 + 2 + … + n integer varyingreturned (out)
4
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 1 + 2 + … + n integer varyingreturned (out) runningTotal A counter integer varying count
5
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 )
6
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
7
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
8
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
9
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.
10
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
11
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
12
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.
13
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!
14
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
15
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!
16
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
17
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
18
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
19
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
20
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
21
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
22
C++ An Introduction to Computing, 3rd ed. 22 Example: Counting Digits Humans looking at a number can easily count digits 63 3291058 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
23
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
24
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; }
25
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
26
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 }
27
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
28
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; }
29
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
30
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
31
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
32
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)
33
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.
34
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
35
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
36
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
37
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 };
38
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
39
C++ An Introduction to Computing, 3rd ed. 39 Inheritance Public variables and methods from parent class available to child class objects
40
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
41
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.