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.

Slides:



Advertisements
Similar presentations
Parameter Passing Mechanisms Reference Parameters.
Advertisements

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 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Control Structures II (Repetition)
Objectives You should be able to describe:
Software Engineering 1 (Chap. 1) Object-Centered Design.
The switch Statement Selection Revisited. Problem Using OCD, design and implement a program that allows the user to perform an arbitrary temperature conversion.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
PRINCIPLES OF PROGRAMMING Revision. A Computer  A useful tool for solving a great variety of problems.  To make a computer do anything (i.e. solve.
1 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
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.
Controlling Function Behavior Sequence, Selection and Repetition.
File I/O ifstreams and ofstreams Sections 11.1 &
C++ Loop Statements Repetition Revisited. Problem Using OCD, design and implement a function that, given a menu, its first valid choice, and its last.
C++ An Introduction to Computing, 3rd ed. 1 Repetition Chapter 7.
1 Simple Functions Writing Reuseable Formulas. In Math Suppose f (x) = 2 x 2 +5Suppose f (x) = 2 x 2 +5 f(5)=?f(5)=? f(5) = 2* =55f(5) = 2*
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.
# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
2Object-Oriented Program Development Using C++ 3 Basic Loop Structures Loops repeat execution of an instruction set Three repetition structures: while,
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
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.
CMP-MX21: Lecture 5 Repetitions Steve Hordley. Overview 1. Repetition using the do-while construct 2. Repetition using the while construct 3. Repetition.
1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)
Software Engineering Object-Centered Design. Problem Solving Does anyone scuba dive? Let’s solve this scuba-diving problem: Write a program that, given.
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.
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
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.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Simple Functions Writing Reuseable Formulas. Problem Using OCD, design and implement a program that computes the area and circumference of an Australian.
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.
Selection Executing Statements Selectively. Review We’ve seen that the C++ if statement permits a Statement to be executed selectively: if (Expression)
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
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)
Introduction to Computer Programming
Controlling Behavior The if and for Statements.
ifstreams and ofstreams
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Repeating the Execution of Statements
More Repetition Chap. 8 (Read § ) 1.
Writing Reuseable Formulas
Programming Fundamentals
solve the following problem...
Looping III (do … while statement)
Chapter 5: Control Structures II (Repetition)
Objectives You should be able to describe: The while Statement
ifstreams and ofstreams
Controlling Behavior The if and for Statements.
Object-Centered Design
Presentation transcript:

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 valid choice, displays that menu, reads a choice from the user, and returns a value guaranteed to be (i) a valid choice from the menu, and (ii) a choice chosen by the user. You may assume that the valid menu choices form a continuous sequence.

3 Preliminary Analysis The tricky part is that the function must return a value that (i) is a valid menu choice; and (ii) was chosen by the user. One way to accomplish both goals is to use a loop that displays the menu, reads the user’s choice, checks its validity, and if it is not valid, gives them another chance...

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

5 Objects Description 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 Operations Description 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 Algorithm 0. Receive MENU, firstChoice, lastChoice. 1. Loop a. Display MENU via cout. b. Read choice from cin. c. If firstChoice <= choice and choice <= lastChoice: terminate repetition. End loop. End loop. 2. Return choice.

8 Organization Note that our algorithm terminates the repetition at the bottom of the loop. To code such loops conveniently and readably, C++ provides the do loop.

9 Coding char GetValidMenuChoice(const string MENU, char firstChoice, char lastChoice) { char choice; do { cout << MENU; cin >> choice; } while (choice lastChoice); return choice; }//menu1.h

10 Discussion The do loop tests its condition at the end of the loop, making it useful for any problem in which the body of the loop must be performed at least once. This function seems general enough to be reuseable by any menu-using program, so it should be stored in a library.

11 Using the Function Once our function is stored in a library, a 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 Testing Please enter: a - to do this b - to do that c - to do the other --> s Please enter: a - to do this b - to do that c - to do the other --> q Please enter: a - to do this b - to do that c - to do the other --> a...

13 Note 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. Our algorithm must be adapted accordingly.

14 Algorithm (revised) 0. Receive MENU, firstChoice, lastChoice. 1. Loop a. Display MENU via cout. b. Read choice from cin. c. If firstChoice <= choice and choice <= lastChoice: terminate repetition. d. Display error message. End loop. End loop. 2. Return choice.

15 Organization Our algorithm no longer terminates the repetition at the bottom of the loop. Instead, it terminates repetition in the middle of the loop, suggesting a forever loop. Which loop is best used depends on where execution leaves the loop in one’s algorithm.

16 Coding 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 Function If a programmer now writes the same 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 Testing Please 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 Review We’ve seen that the C++ for loop permits a statement to be executed repeatedly: for (Expr 1 ; Expr 2 ; Expr 3 ) Statement Expr 1 Expr 2 Statement Expr 3 F T

20 A Counting Loop The for loop is 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

21 Other Loops C++ also provides 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!

22 Pretest Loops If StatementList 1 is omitted from a forever loop, we get a test-at-the-top or pretest loop: for (;;) { if (Expression) break; StatementList 2 } Expression F T StatementList 2

23 The while Loop For such situations, C++ provides the more readable while loop, whose 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!

24 Post-test Loops If StatementList 2 is omitted in a forever loop, we get a test-at-the-bottom or post-test loop: for (;;) { StatementList 1 if (Expression) break; } Expression FT StatementList 1

25 The do Loop For such situations, C++ provides the more readable do loop, whose pattern is: 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

26 Choosing a Loop With four loops at our disposal, how do we know which one to use? Use the for loop for counting problems.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: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.

27 Example: Bouncing Ball Problem When a ball is dropped, it bounces to ½ of its previous height.When a ball is dropped, it bounces to ½ of its previous height. We seek a program which simulates thisWe 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 realvaryingheight bounce number integervaryingbounce some small number realconstantSMALL_NUMBER Objects

28 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

29 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

30 Coding and Testing Note use of while loop, Figure 7.4Note use of while loop, Figure 7.4Figure 7.4Figure 7.4 –Instead of a pretest forever for loop Note sample runNote sample runsample runsample run

31 #include // >, cout, cin using 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 height of the rebounds of a dropped ball. Enter the starting height (in meters): 15 Starting height: 15 meters Rebound # 1: 7.5 meters Rebound # 2: 3.75 meters Rebound # 3: meters Rebound # 4: meters Rebound # 5: meters Rebound # 6: meters Rebound # 7: meters Rebound # 8: meters Rebound # 9: meters Rebound # 10: meters Rebound # 11: meters Rebound # 12: meters Rebound # 13: meters Rebound # 14: meters

33 Discussion The four C++ loops provide very different behaviors: The for loop is a loop designed for counting that provides pretest behavior.The for loop is a loop designed for counting that provides pretest behavior. The while loop is a general-purpose loop that provides test-at-the-top behavior.The while loop is a general-purpose loop that provides test-at-the-top behavior. The do loop is a general-purpose loop that provides test-at-the-bottom behavior.The do loop is a general-purpose loop that provides test-at-the-bottom behavior. The forever loop is a general-purpose loop that provides test-in-the-middle behavior.The forever loop is a general-purpose loop that provides test-in-the-middle behavior.

34 Discussion The while and for loops have their tests at the top, implying that if the loop’s condition is initially false, the body of the loop will not execute, which is called. The while and for loops have their tests at the top, implying that if the loop’s condition is initially false, the body of the loop will not execute, which is called zero-trip behavior. The do loop has its test at the bottom, implying that the body of the loop will execute at least once, regardless of the value of the loop’s condition, which is called. The do loop has its test at the bottom, implying that the body of the loop will execute at least once, regardless of the value of the loop’s condition, which is called one-trip behavior.

35 Discussion The forever loop its test in the middle: –Statements in StatementList 1 will be executed at least once, regardless of the value of Expression. –Statements in StatementList 2 will not be executed if Expression causes repetition to terminate. This might be called. This might be called half-trip behavior.

36 Summary 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- middle loop.The forever loop, a general-purpose test-in-the- middle loop. Which loop you use to solve a given problem should be determined by your algorithm for that problem.

37 Problem Session Working in pairs of two, solve the following problem...

38 Problem Write a function that receives any non-negative int, and returns an int whose value is the digits of the received value in reversed order. Examples: Reverse(123) == 321 Reverse(Reverse(123)) == 123 You should not use a string to solve this problem!

39 Coding /* 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 Note 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 in the body of a loop consumes time every repetition of the loop, which can significantly slow one’s program.