1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)

Slides:



Advertisements
Similar presentations
Alice in Action with Java Chapter 10 Flow Control in Java.
Advertisements

Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
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)
Chapter 5: Loops and Files.
Alice in Action with Java Chapter 10 Flow Control in Java.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Chapter 5: Control Structures II (Repetition)
Selection. Computer Programming 2 Objectives Examine if statement in more detail Study use of switch statement to implement multialternative selections.
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)
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.
Java Programming: From the Ground Up
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Controlling Function Behavior Sequence, Selection and Repetition.
C++ Loop Statements Repetition Revisited. Problem Using OCD, design and implement a function that, given a menu, its first valid choice, and its last.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
C++ An Introduction to Computing, 3rd ed. 1 Repetition Chapter 7.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
1 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
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.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
+ 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.
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.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: The while Statement cin within a while Loop The for.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
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 5 Repetition. 2 Objectives You should be able to describe: The while Statement cin within a while Loop The for Statement The do Statement Common.
1 1 Additional Control Structures Chapter 9 2 New and Improved... Ways to branch Ways to write loops Understanding the break and continue statements.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
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.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Controlling Behavior The if and for Statements.
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II (Repetition)
More Repetition Chap. 8 (Read § ) 1.
Control Structures II (Repetition)
Control Structures - Repetition
Looping III (do … while statement)
Chapter 5: Control Structures II (Repetition)
Controlling Behavior The if and for Statements.
Presentation transcript:

1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)

Are there any Weaknesses in the if Statement? For some problems, the "waterfall" execution of the multi-branch if leads to poor (or perhaps unacceptable) performance of a program. Example: Suppose we need a function that, given the number of a day of the week (1-7), computes its corresponding name (Sunday- Saturday)? 2

Algorithm: 0. Receive dayNumber. 1. If dayNumber == 1: Return "Sunday". Else if dayNumber == 2: Return "Monday". Else if dayNumber == 3: Return "Tuesday". Else if dayNumber == 4: Return "Wednesday". Else if dayNumber == 5: Return "Thursday". Else if dayNumber == 6: Return "Friday". Else if dayNumber == 7: Return "Saturday". Else Display an error message, and return "". 3

// Receive a day number, return its name string dayName(int dayNumber) { if (dayNumber == 1) return "Sunday"; else if (dayNumber == 2) return "Monday"; else if (dayNumber == 3) return "Tuesday"; else if (dayNumber == 4) return "Wednesday"; else if (dayNumber == 5) return "Thursday"; else if (dayNumber == 6) return "Friday"; else if (dayNumber == 7) return "Saturday"; else { cerr << "\n** DayName: invalid day number\n"; return ""; } 4

The multi-branch if has ______________________ time: Computing "Sunday" requires ___ comparison Computing "Sunday" requires ___ comparison Computing "Monday" requires ___ comparisons Computing "Monday" requires ___ comparisons Computing "Saturday" requires ___ comparisons Computing "Saturday" requires ___ comparisons Computations that are "later" in the if take longer.  Computations that are "later" in the if take longer. There are situations where the time to select one of many statements must be ________________. 5

A Solution The C++ _________ statement provides an alternative: string DayName(int dayNumber) { ________________________________ ___ _____________________ _____________________________ case 2: return "Tuesday"; case 3: return "Wednesday"; case 4: return "Wednesday"; case 5: return "Thursday"; case 6: return "Friday"; case 7: return "Saturday"; _____________ cerr << "\n* DayName: invalid day number\n"; return ""; ___ } 6 Cases need not be in order nor consecutive, and there can be multiple labels.

The switch Statement The switch statement provides multi-branch selection, but guarantees _________________________, regardless of which branch is selected. Thus, the time to select return "Saturday"; is identical to the time to select return "Sunday"; if a switch statement is used to select them. 7

8 Pattern: switch (expression) { caseList 1 StatementList 1 caseList 2 StatementList 2... caseList N StatementList N default: StatementList N+1 } where expression is an integer-compatible expression, each caseList is one or more cases of this form: case ConstantValue : and each StatementList usually ends with a break or return statement.

Warning C++ switch statements exhibit ________________ behavior. 1. expression is evaluated. 2. If expression == constant i, control jumps to the Statement associated with constant i. 3. Control continues ______________ until: 3. Control continues ______________ the switch statement until: a. The end of the switch is reached; b. A is executed, terminating the switch; b. A break is executed, terminating the switch; c. A is executed, terminating the function; or c. A return is executed, terminating the function; or d. An is executed, terminating the program. d. An exit() is executed, terminating the program. 9

Output: ______________________________ 10 Example What will the following statement display, if the value of is 6? What will the following statement display, if the value of dayNumber is 6? switch(dayNumber) { case 1: cout << "Sunday"; case 2: cout << "Monday"; case 3: cout << "Tuesday"; case 4: cout << "Wednesday"; case 5: cout << "Thursday"; case 6: cout << "Friday"; case 7: cout << "Saturday"; default: cout << "Error!" << endl; }

Solution 11 To avoid the "drop- through" behavior, we need to add a _________ To avoid the "drop- through" behavior, we need to add a _________ or ____________ statement at the end of each case: switch(dayNumber) { case 1: cout << "Sunday"; break; case 2: cout << "Monday"; break; case 3: cout << "Tuesday"; break; case 4: cout << "Wednesday"; break; case 5: cout << "Thursday"; break; case 6: cout << "Friday"; break; case 7: cout << "Saturday"; break; default: cout << "Error!" << endl; } Output when is 6? _______________ Output when dayNumber is 6? _______________

Other Repetition Structures count = first count <= last Statement count++ F T 12 The most common use of for loops is to count from one value first to another value last: for (int count = first; count <= last; count++) Statement Or to count down from a larger value to a smaller one: for (int count = first; count >= last; count--) Statement

More General Loops 13 For example, in the structure pictured at the right, repetition continues so long as some Condition is true. But sometimes — e.g., when reading data — we need a more general repetition structure  one in which we don't know in advance how many iterations will be needed. StatementList 1 Condition T F StatementList 2

The while Loop For such situations, C++ provides the while loop: while (Condition) Statement Condition T F Statement Statement is almost always a compound C++ statement. Repetition continues while Condition is true. 14

Post-test Loops If StatementList 2 is omitted in our general repetition structure, we get a test-at-the-__________ or ___________ loop. 15 Condition TF StatementList 1

The do Loop For such situations, C++ provides the do loop: do Statement while (Condition); Condition TF Statement 16 Statement is almost always a compound C++ statement. Repetition "does" Statement while Condition is true. NOTE!

The do-loop is good for query-controlled input loops: do { cout << "\nEnter a failure time: "; cin >> failureTime; failureTimeSum += failureTime; numComponents++; cout << "Do you have more data to enter (y or n)? "; cin >> response; } while (response == 'y' || response == 'Y'); 17 The do-loop is good for fool-proofing input loops:do{ Prompt for a menu selection and have the user enter it Prompt for a menu selection and have the user enter it} while ( not a valid menu selection ); Could use in main( ) of Proj. 6

More general loops like that pictured earlier in which the termination test is made neither at the top nor the bottom of the loop are sometimes called test-in-the-middle loops. Note: The"T" and "F" labels on Condition have been switched here so that repetition terminates when Condition becomes true. This makes it easier to implement this structure. StatementList 1 Condition F T StatementList 2 Test-in-the-Middle Loops 18

Such test-in-the-middle loops can be implemented in C++ with a for-loop of the form: for (;;) { StatementList 1 if (Condition) break; StatementList 2 } StatementList 1 Condition F T StatementList 2 Because the for clause contains no expressions to control repetition (thus allowing an infinite loop), this is sometimes called a _______________. // or while (true) Forever Loops 19

The forever loop is very useful for constructing sentinel-controlled input loops: for (;;) { Input dataValue ________________________________________ Process dataValue } Note that when the sentinel value is input, it does not get processed as a "regular" data value. Also note that if the sentinel value is the first value entered, repetition terminates immediately. // or while (true) Test-in-the-Middle Input Loops 20 Good to set off termination test with blank line before and after it.

// Read, count, find mean of a list of numbers int count = 0; double value, sum = 0, mean; for (;;) { cout > value; _______________________________________ count++; sum += value; } if (count == 0) cerr << "No values entered\n"; else mean = sum / count; An Example 21

Summary C++ provides four repetition statements: The for loop, for counting. The while loop, a general-purpose pretest loop. The do loop, a general-purpose post-test loop. The forever loop, a general-purpose test-in- the-middle loop. 22

The four C++ loops provide very different behaviors: 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 (pretest) behavior. The do loop is a general-purpose loop that provides test-at-the-bottom (post-test) behavior. The forever loop is a general-purpose loop that provides test-in-the-middle behavior. 23

Choosing a Loop: Use the for loop for problems that require counting over some range of values. For other problems, identify the condition needed to terminate repetition and then determine whether execution needs to:use a: skip the loop body if terminationwhile loop condition doesn't hold go through the body at leastdo loop once before checking termination condition go through the first part of loop forever loop body before checking termination condition and skip second part if it holds 24