1 C++ Loop Statements Repetition Revisited. 2 Problem Using OCD, design and implement a function...

40
1 C++ Loop Statements C++ Loop Statements Repetition Revisited Repetition Revisited

Transcript of 1 C++ Loop Statements Repetition Revisited. 2 Problem Using OCD, design and implement a function...

1

C++ Loop StatementsC++ Loop Statements

Repetition RevisitedRepetition Revisited

2

ProblemProblem

Using OCD, design and implement a function that, given a Using OCD, design and implement a function that, given a menu, its first valid choice, and its last valid choice, menu, its first valid choice, and its last valid choice, displays that menu, reads a choice from the user, and displays that menu, reads a choice from the user, and returns a value guaranteed to be (i) a valid choice from returns a value guaranteed to be (i) a valid choice from the menu, and (ii) a choice chosen by the user. the menu, and (ii) a choice chosen by the user.

You may assume that the valid menu choices form a You may assume that the valid menu choices form a continuous sequence.continuous sequence.

3

Preliminary AnalysisPreliminary Analysis

The tricky part is that the function must The tricky part is that the function must return a value thatreturn a value that

(i) is a valid menu choice; and(i) is a valid menu choice; and

(ii) was chosen by the user.(ii) was chosen by the user.

One way to accomplish both goals is to One way to accomplish both goals is to use a loop that displays the menu, use a loop that displays the menu, reads the user’s choice, checks its reads the user’s choice, checks its validity, and if it is not valid, gives them validity, and if it is not valid, gives them another chance...another chance...

4

BehaviorBehavior

Our function should receive a menu, its Our function should receive a menu, its first valid choice and its last valid first valid choice and its last valid choice. It should repeatedly display choice. It should repeatedly display the menu, read the user’s choice, so the menu, read the user’s choice, so long as the user’s choice is invalid. It long as the user’s choice is invalid. It should then return the user’s choice.should then return the user’s choice.

5

ObjectsObjects

Description Type Kind NameDescription Type Kind Name

first valid char variable firstChoice choice

last valid char variable lastChoice choice

user’s choice char variable choice

menu string constant MENU

6

OperationsOperations

Description Predefined? Library? NameDescription Predefined? Library? Name

display strings yes iostream <<read a char yes iostream >>check validity no built-in <=, &&repeat steps yes built-in ?

terminate loop yes built-in ?

return a char yes built-in return

7

AlgorithmAlgorithm

0. Receive 0. Receive MENUMENU, , firstChoicefirstChoice, , lastChoicelastChoice..

1. Loop1. Loop

a. Display a. Display MENUMENU via via coutcout..

b. Read b. Read choicechoice from from cincin..

c. If c. If firstChoicefirstChoice <= <= choicechoice and and choicechoice <= <= lastChoicelastChoice: :

terminate repetition.terminate repetition.

End loop.End loop.

2. Return 2. Return choicechoice..

8

OrganizationOrganization

Note that our algorithm terminates the Note that our algorithm terminates the repetition at the repetition at the bottombottom of the loop. of the loop.

To code such loops conveniently and To code such loops conveniently and readably, C++ provides the readably, C++ provides the dodo loop. loop.

9

CodingCoding

char GetValidMenuChoice(const string MENU,char firstChoice, char lastChoice)

{ char choice; do { cout << MENU; cin >> choice; } while (choice < firstChoice || choice > lastChoice);

return choice;}//menu1.h

10

DiscussionDiscussion

The do loop tests its condition at the end The do loop tests its condition at the end of the loop, making it useful for any of the loop, making it useful for any problem in which the body of the loop problem in which the body of the loop must be performed must be performed at least onceat least once..

This function seems general enough to This function seems general enough to be reuseable by any menu-using be reuseable by any menu-using program, so it should be stored in a program, so it should be stored in a library.library.

11

Using the FunctionUsing the Function

Once our function is stored in a library, a Once our function is stored in a library, a programmer can write something like this:programmer can write something like this:

#include “Menu.h”

int main(){ const string MENU = “Please enter:\n” “ a - to do this\n” “ b - to do that\n” “ c - to do the other\n” “--> “;

char choice = GetValidMenuChoice(MENU, ‘a’, ‘c’);

// ...}//menu.cpp

12

TestingTestingPlease enter: a - to do this b - to do that c - to do the other--> sPlease enter: a - to do this b - to do that c - to do the other--> qPlease enter: a - to do this b - to do that c - to do the other--> a...

13

NoteNoteIf we wish to display an error message, that changes our algorithm...If we wish to display an error message, that changes our algorithm...

Such a message should only be displayed if the user enters an invalid value, but should be displayed each time they do so.Such a message should only be displayed if the user enters an invalid value, but should be displayed each time they do so.

Our algorithm must be adapted accordingly.Our algorithm must be adapted accordingly.

14

Algorithm (Algorithm (revisedrevised))

0. Receive 0. Receive MENUMENU, , firstChoicefirstChoice, , lastChoicelastChoice..

1. Loop1. Loop

a. Display a. Display MENUMENU via via coutcout..

b. Read b. Read choicechoice from from cincin..

c. If c. If firstChoicefirstChoice <= <= choicechoice and and choicechoice <= <= lastChoicelastChoice: :

terminate repetition.terminate repetition.

d. Display error message.

End loop.End loop.

2. Return 2. Return choicechoice..

15

OrganizationOrganization

Our algorithm no longer terminates the Our algorithm no longer terminates the repetition at the repetition at the bottombottom of the loop. of the loop.

Instead, it terminates repetition in the Instead, it terminates repetition in the middle of the loop, suggesting a middle of the loop, suggesting a forever loopforever loop..

Which loop is best used depends on Which loop is best used depends on where execution leaves the loop in where execution leaves the loop in one’s one’s algorithmalgorithm..

16

CodingCoding

char GetValidMenuChoice(const string MENU,char firstChoice, char lastChoice)

{ char choice; for (;;) { cout << MENU; cin >> choice;

if (choice >= firstChoice && choice <= lastChoice) break;

cerr << “\n*** Invalid menu choice: \’“ << choice << “\’ entered.\n” << endl; }

return choice;}//menu.h

17

Using the FunctionUsing the Function

If a programmer now writes the same If a programmer now writes the same thing:thing:

#include “Menu.h”

int main(){ const string MENU = “Please enter:\n” “ a - to do this\n” “ b - to do that\n” “ c - to do the other\n” “--> “;

char choice = GetValidMenuChoice(MENU, ‘a’, ‘c’);

// ...}

18

TestingTestingPlease enter: a - to do this b - to do that c - to do the other--> s

** Invalid menu choice ‘s’ entered.

Please enter: a - to do this b - to do that c - to do the other--> a...

19

ReviewReviewWe’ve seen that the C++ We’ve seen that the C++ for for

looploop permits a statement to permits a statement to be executed repeatedly:be executed repeatedly:

for (Expr1; Expr2; Expr3)Statement

Expr1

Expr2

Statement

Expr3

F

T

20

A Counting LoopA Counting Loop

The for loop is most The for loop is most commonly used to commonly used to count from one count from one value value firstfirst to to another value another value lastlast::

for (int count = first; count <= last; count++)

Statement

count = first

count <= last

Statement

count++

F

T

21

Other LoopsOther LoopsC++ also provides the forever loop: C++ also provides the forever loop:

a for loop without expressions:a for loop without expressions:

for (;;){StatementList1

if (Expression) break; StatementList2}

StatementList1

Expression

F

T

StatementList2

Repetition continues so long Repetition continues so long as as ExpressionExpression is is falsefalse!!

22

Pretest LoopsPretest Loops

If If StatementListStatementList11 is omitted from a forever is omitted from a forever loop, we get a loop, we get a test-at-the-top test-at-the-top oror pretest pretest loop:loop:

for (;;){ if (Expression) break; StatementList2}

Expression

F

T

StatementList2

23

The while LoopThe while LoopFor such situations, C++ provides the more For such situations, C++ provides the more

readable readable while loopwhile loop, whose pattern is:, whose pattern is:

while (Expression) Statement Expression

T

F

StatementStatementStatement can be either a can be either a

single or compound C++ single or compound C++ statement.statement.

Repetition continues so Repetition continues so long as long as ExpressionExpression is is truetrue!!

24

Post-test LoopsPost-test Loops

If If StatementListStatementList22 is omitted in a forever loop, is omitted in a forever loop, we get a we get a test-at-the-bottom test-at-the-bottom oror post-test post-test loop:loop:

for (;;){ StatementList1 if (Expression) break;}

Expression FT

StatementList1

25

The do LoopThe do LoopFor such situations, C++ provides the For such situations, C++ provides the

more readable more readable do loopdo loop, whose pattern is:, whose pattern is:

do Statementwhile (Expression);

StatementStatement can be either a can be either a single or compound C++ single or compound C++ statement.statement.

Repetition continues so Repetition continues so long as long as ExpressionExpression is is truetrue!!

Expression TF

Statement

26

Choosing a LoopChoosing a Loop

With four loops at our disposal, how do we With four loops at our disposal, how do we know which one to use?know which one to use?

• Use the Use the forfor loop for counting problems. loop for counting problems.

• Design algorithms for non-counting problems Design algorithms for non-counting problems using a general Loop statement, and see using a general Loop statement, and see where it is appropriate for repetition to where it is appropriate for repetition to terminate:terminate:– If at the loop’s beginning, use the If at the loop’s beginning, use the whilewhile loop loop

– If at its end, use the If at its end, use the dodo loop loop

– If in its middle, use the If in its middle, use the foreverforever loop. loop.

27

Example: Bouncing Ball Example: Bouncing Ball ProblemProblem• When a ball is dropped, it bouncesWhen a ball is dropped, it bouncesto ½ of its previous height. to ½ of its previous height.

• We seek a program which simulates thisWe seek a program which simulates this– Display number of each bounce and heightDisplay number of each bounce and height

– Repeat until bounce height is very smallRepeat until bounce height is very small

DescriptionDescriptionSoftware ObjectsSoftware Objects

TypeType KindKind NameName

current heightcurrent height realreal varyingvarying heightheight

bounce numberbounce number integerinteger varyingvarying bouncebounce

some small numbersome small number realreal constantconstant SMALL_NUMBERSMALL_NUMBER

Objects

28

OperationsOperationsi.i. Input a real value, the original Input a real value, the original heightheight

ii.ii. Initialize Initialize bouncebounce to zero to zero

iii.iii. Divide Divide heightheight by 2 for rebound height by 2 for rebound height

iv.iv. Increment Increment bouncebounce

v.v. Display current Display current bouncebounce number, number, heightheight

vi.vi. Repeat iii – v as long asRepeat iii – v as long as height height ≥ SMALL_NUMBER≥ SMALL_NUMBER

29

AlgorithmAlgorithm1.1. Initialize Initialize bouncebounce 0 02.2. Prompt for, read value for Prompt for, read value for heightheight

3.3. Display original Display original heightheight value with value with labellabel

4.4. Loop:Loop:a.a. If If height < SMALL_NUMBERheight < SMALL_NUMBER, terminate, terminateb.b. Replace Replace heightheight with with height / 2height / 2c.c. Add 1 to Add 1 to bouncebounced.d. Display Display bouncebounce and he and heiightght

5.5. End loopEnd loop

30

Coding and TestingCoding and Testing

• Note use of Note use of whilewhile loop, loop, Figure 7.4Figure 7.4– Instead of a Instead of a

pretest forever pretest forever forfor loop loop

• Note Note sample runsample run

31

#include <iostream> // <<, >>, cout, cinusing namespace std;

int main(){ const double SMALL_NUMBER = 1.0e-3; // 1 millimeter cout << "This program computes the number and height\n"

<< "of the rebounds of a dropped ball.\n"; cout << "\nEnter the starting height (in meters): "; double height; cin >> height; cout << "\nStarting height: " << height << " meters\n"; int bounce = 0; while (height >= SMALL_NUMBER) {

height /= 2.0;bounce++;cout << "Rebound # " << bounce << ": " << height << " meters" << endl;

}}

32

Sample run:

This program computes the number and heightof the rebounds of a dropped ball.

Enter the starting height (in meters): 15Starting height: 15 metersRebound # 1: 7.5 metersRebound # 2: 3.75 metersRebound # 3: 1.875 metersRebound # 4: 0.9375 metersRebound # 5: 0.46875 metersRebound # 6: 0.234375 metersRebound # 7: 0.117188 metersRebound # 8: 0.0585938 metersRebound # 9: 0.0292969 metersRebound # 10: 0.0146484 metersRebound # 11: 0.00732422 metersRebound # 12: 0.00366211 metersRebound # 13: 0.00183105 metersRebound # 14: 0.000915527 meters

33

DiscussionDiscussion

The four C++ loops provide very different The four C++ loops provide very different behaviors:behaviors:

• The The for loopfor loop is a loop designed for counting that is a loop designed for counting that provides pretest behavior.provides pretest behavior.

• The while loop is a general-purpose loop that The while loop is a general-purpose loop that provides test-at-the-top behavior.provides test-at-the-top behavior.

• The do loop is a general-purpose loop that The do loop is a general-purpose loop that provides test-at-the-bottom behavior.provides test-at-the-bottom behavior.

• The forever loop is a general-purpose loop that The forever loop is a general-purpose loop that provides test-in-the-middle behavior.provides test-in-the-middle behavior.

34

DiscussionDiscussion

The The whilewhile and and forfor loops have their tests at the loops have their tests at the top, implying that top, implying that if the loop’s condition is if the loop’s condition is initially false, the body of the loop will not initially false, the body of the loop will not executeexecute, which is called , which is called zero-trip behavior..

The The dodo loop has its test at the bottom, implying loop has its test at the bottom, implying that that the body of the loop will execute at the body of the loop will execute at least once, regardless of the value of the least once, regardless of the value of the loop’s conditionloop’s condition, which is called , which is called one-trip behavior. .

35

DiscussionDiscussion

The forever loop its test in the middle: The forever loop its test in the middle:

– Statements in Statements in StatementListStatementList11 will be will be executed executed at least onceat least once, regardless of the , regardless of the value of value of ExpressionExpression..

– Statements in Statements in StatementListStatementList22 will will not be not be executedexecuted if if ExpressionExpression causes repetition to causes repetition to terminate.terminate.

This might be called This might be called half-trip behavior..

36

SummarySummary

C++ provides four repetitive execution statements:C++ provides four repetitive execution statements:

• The for loop, for counting.The for loop, for counting.

• The while loop, a general-purpose pretest loop.The while loop, a general-purpose pretest loop.

• The do loop, a general-purpose post-test loop.The do loop, a general-purpose post-test loop.

• The forever loop, a general-purpose test-in-the-The forever loop, a general-purpose test-in-the-middle loop.middle loop.

Which loop you use to solve a given problem Which loop you use to solve a given problem should be determined by your should be determined by your algorithmalgorithm for that for that problem.problem.

37

Problem SessionProblem Session

Working in pairs of two,Working in pairs of two,

solve the following problem...solve the following problem...

38

ProblemProblem

Write a function that receives any non-negative Write a function that receives any non-negative int, and returns an int whose value is the digits int, and returns an int whose value is the digits of the received value in reversed order.of the received value in reversed order.

Examples: Examples:

Reverse(123) == 321Reverse(123) == 321

Reverse(Reverse(123)) == 123Reverse(Reverse(123)) == 123

You should not use a string to solve this problem!You should not use a string to solve this problem!

39

CodingCoding

/* Reverse() * Receive: number, an int. * PRE: number >= 0. * Return: the int consisting of number’s digits reversed. */

int Reverse(int number){ int answer = 0; // our result int rightDigit; // rightmost digit

while (number > 0) // while digits remain { rightDigit = number % 10; // get rightmost digit answer *= 10; // L-shift answer’s digits answer += rightDigit; // add in new digit number /= 10; // chop rightmost digit }

return answer;}

40

Efficiency NoteEfficiency Note

Avoid declaring variables within loops, e.g.Avoid declaring variables within loops, e.g.for (;;)

{ int rightDigit = number % 10; if (number > 0) break; answer *= 10; answer += rightDigit; number /= 10; }

Processing a declaration consumes time.Processing a declaration consumes time.

Processing a declaration in the body of a Processing a declaration in the body of a loop consumes time loop consumes time every repetition of every repetition of the loopthe loop, which can significantly slow , which can significantly slow one’s program.one’s program.