410 likes | 444 Views
Repetition. Chapter 7. 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.
E N D
Repetition Chapter 7 C++ An Introduction to Computing, 3rd ed.
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.
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. C++ An Introduction to Computing, 3rd ed.
Steps Required • Procedure will require: • Initialize a running total to 0 • Initialize a count to 1 • Loop through: • Add count to the running total • Add 1 to count • Additional objects now seen: C++ An Introduction to Computing, 3rd ed.
Operations Operations • Receive an integer (n) • Initialize integers, runningTotal= 0, count = 1 • Add two integers, count and runningTotal, store result • Repeat step iii, for each value of count = 1 through n • Return the integer (runningTotal) C++ An Introduction to Computing, 3rd ed.
Note use of for loop to do step 2 of the algorithm Algorithm, Coding, Testing Algorithm for summation: • Initialize runningTotal to 0 • For each value of count in range 1 through n • Add count to runningTotal • Return runningTotal • View function source code, Figure 7.1 • Driver program, Figure 7.2 • Sample runs of Figure 7.2 C++ An Introduction to Computing, 3rd ed.
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.
count = first F count <= last T Statement count++ 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 C++ An Introduction to Computing, 3rd ed.
InitializerExpr F LoopCondition T Statement Note: if the LoopCondition is initially false, then the body of the loop will not be executed even once. IncrementExpr The for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement • When LoopCondition becomes false, • Control proceeds to the next statement. C++ An Introduction to Computing, 3rd ed.
count = first count = first F count <= last count <= last F T T Statement Statement count++ count++ Nested Loops • Consider the statement in a for loop • It can be any kind of statement • Including another for statement C++ An Introduction to Computing, 3rd ed.
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.3 And the sample run C++ An Introduction to Computing, 3rd ed.
Noncounting Loops • One of the quirks of the C++ for loop • Its three expressions can be omitted: 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.
StatementList1 T Expression F StatementList2 Noncounting Loops • This is the forever loop • a for loop without expressions: for (;;) { StatementList1 if (Expression) break; StatementList2 } • Repetition continues so long as Expression is false! C++ An Introduction to Computing, 3rd ed.
T Expression F StatementList2 Pretest Loops • If StatementList1 is omitted from forever loop – results in • A test-at-the-top or pretest loop: for (;;) { if (Expression) break; StatementList2 } StatementList1 C++ An Introduction to Computing, 3rd ed.
F Expression T Statement The while Loop • For such situations, C++ provides the more readable while loop, • pattern is: while (Expression) 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.
Example: Bouncing Ball Problem • When a ball is dropped, it bouncesto ½ 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 Objects C++ An Introduction to Computing, 3rd ed.
Operations • Input a real value, the original height • Initialize bounce to zero • Divide height by 2 for rebound height • Increment bounce • Display current bounce number, height • Repeat iii – v as long asheight ≥ SMALL_NUMBER C++ An Introduction to Computing, 3rd ed.
Algorithm • Initialize bounce 0 • Prompt for, read value for height • Display original height value with label • Loop: • If height < SMALL_NUMBER, terminate • Replace height with height / 2 • Add 1 to bounce • Display bounce and height • End loop C++ An Introduction to Computing, 3rd ed.
Coding and Testing • Note use of while loop, Figure 7.4 • Instead of a pretest forever for loop • Note sample run C++ An Introduction to Computing, 3rd ed.
StatementList1 T Expression F Post-test Loops • If StatementList2 is omitted in a forever loop – results in • a test-at-the-bottom orpost-test loop: for (;;) { StatementList1 if (Expression) break; } StatementList2 C++ An Introduction to Computing, 3rd ed.
Statement F Expression T 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! C++ An Introduction to Computing, 3rd ed.
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 C++ An Introduction to Computing, 3rd ed.
Objects and Operations Operations: • Integer division (intValue/ 10) • Integer addition (add 1 to numDigits) • Repetition of i and ii as long as intValue is not 0 C++ An Introduction to Computing, 3rd ed.
Algorithm • Initialize numDigits to 0 • Loop • Increment numDigits • Divide intValue by 10, store result in intValue • If intValue is 0, terminate repetition • Return numDigits • Note – we could use a forever for loopfor ( ; ; ) { numDigits++; intValue /= 0; if (intValue == 0) break; } C++ An Introduction to Computing, 3rd ed.
Coding and Testing • Note that the source code, Figure 7.5 uses a do loop instead • Observe the driver program, Figure 7.6 • Sample Runs C++ An Introduction to Computing, 3rd ed.
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 } C++ An Introduction to Computing, 3rd ed.
Forever loop Example • Read and average a list of test scores: 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); } } C++ An Introduction to Computing, 3rd ed.
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 loopcout << "Enter a failure time (-1 to quit) :";cin >> failureTime;while (failureTime >= 0) { failureTimeSum += failureTime; numComponents++; cout << "Enter a failure time (-1 to quit) : "; cin >> failureTime;} C++ An Introduction to Computing, 3rd ed.
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.8for ( ; ; ) { cin.get(ch); if (cin.eof()) break; cout << '"\t' >> int (ch) << endl; } C++ An Introduction to Computing, 3rd ed.
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 aftereof mark! • Note program in Figure 7.9 which illustrates this C++ An Introduction to Computing, 3rd ed.
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.10 C++ An Introduction to Computing, 3rd ed.
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.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.
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.
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.
Intro to Algorithm Analysis • So in general: • Thus possible to write a non looping version of our sum functionint sum (int n){ return n * (n + 1) / 2;} • A better algorithm • Takes many less operations C++ An Introduction to Computing, 3rd ed.
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.
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.
Inheritance • TitleName class derived from Name • Figure 7.13 • Driver program with sample run, Figure 7.14 C++ An Introduction to Computing, 3rd ed.
Inheritance • Public variables and methods from parent class available to child class objects C++ An Introduction to Computing, 3rd ed.
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.
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 C++ An Introduction to Computing, 3rd ed.