Calvin College Controlling Behavior The if, switch and for Statements.

Slides:



Advertisements
Similar presentations
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
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)
Alice in Action with Java Chapter 10 Flow Control in Java.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Selection. Computer Programming 2 Objectives Examine if statement in more detail Study use of switch statement to implement multialternative selections.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Control Structures - Repetition Chapter 5 2 Chapter Topics Why Is Repetition Needed The Repetition Structure Counter Controlled Loops Sentinel Controlled.
Presented by Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 12 Boolean Expressions, Switches, For-Loops Chapter 7.
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.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Controlling Function Behavior Sequence, Selection and Repetition.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition 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.
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.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
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.
1 Control Structures The if, for, and while Statements §5.1, §5.4, & §5.5 (Several examples here; also Lab #4) st. line.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 05 (Part III) Control Statements: Part II.
Control Structures Repetition or Iteration or Looping Part II.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
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.
1 More Control Structures if and switch (Chap. 8) do-while and forever loops (Chap. 9)
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Overview Go over parts of quiz? Another iteration structure for loop.
Functions Chapter 4. C++ An Introduction to Programming, 3rd ed. 2 Objectives Study software development using OCD Take a first look at building functions.
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.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Selection Executing Statements Selectively. Review We’ve seen that the C++ if statement permits a Statement to be executed selectively: if (Expression)
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
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 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.
Control Structures 1 The if, for, and while Statements §5.1, §5.4, & §5.5 (Several examples here; also Lab #4)
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 2: Control Structures (Selection & Repetition)
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Infinite for Loop If you omit the test condition, the value is assumed to be TRUE so the loop will continue indefinitely unless you provide some other.
Introduction to Computer Programming
Controlling Behavior The if and for Statements.
REPETITION CONTROL STRUCTURE
Control Structures II (Repetition)
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Control Structures - Repetition
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Alternate Version of STARTING OUT WITH C++ 4th Edition
3 Control Statements:.
Chapter 4: Control Structures I (Selection)
Let’s all Repeat Together
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Controlling Behavior The if and for Statements.
Presentation transcript:

Calvin College Controlling Behavior The if, switch and for Statements

Function Behavior The behavior of a function is determined by the statements within the function. Statements fall into one of three categories: Statements that simply execute in sequence.Statements that simply execute in sequence. Statements that select one of several alternatives.Statements that select one of several alternatives. Statements that repeat another statement.Statements that repeat another statement.

Sequential execution C++ statements are executed one after another (or in sequence) by default: { Statement 1 Statement 2... Statement N } The C++ compound statement (or block) can be thought of as a statement for eliciting sequential execution of a series of statements.

Selective Execution By contrast, there are situations in which a problem’s solution requires that a statement be executed selectively, based on a condition (a boolean expression): if (Condition) Statement 1 [ else Statement 2 ] The C++ if statement is a statement for eliciting selective execution of a statement, allowing a program to choose to execute either Statement 1 or Statement 2, but not both.

The Simple if The C++ if statement has several different forms. The first form has no or Statement 2, and is called the simple if: The first form has no else or Statement 2, and is called the simple if: if (Condition) Statement If Condition is true, Statement is executed; otherwise Statement is skipped. Condition Statement T F

The Two-Branch if In the second form of if, the and Statement 2 are present: In the second form of if, the else and Statement 2 are present: if (Condition) Statement 1 else Statement 2 If Condition is true, Statement 1 is executed and Statement 2 is skipped; otherwise Statement 1 is skipped and Statement 2 is executed. Condition Statement 1 T F Statement 2

The Multi-branch if The if’s final form has a nested if as Statement 2 : if (Cond 1 ) Stmt 1 else if (Cond 2 ) Stmt 2... else if (Cond N ) Stmt N else Stmt N+1 Cond 1 Stmt 1 T F Stmt 2 Cond 2 TF Stmt N Cond N TF Stmt N+1...

Multibranch if Behavior If Condition 1 is true, Statement 1 is executed and the remaining statements are skipped; otherwise, control moves to Condition 2 ; if Condition 2 is true, Statement 2 is executed and the remaining statements are skipped; otherwise control goes to the next condition... if Condition N is true Statement N is executed and Statement N+1 is skipped; otherwise, Statement N+1 is executed.

Multibranch if This form is useful when you must select one of several alternatives: if (score >= 90) grade = ‘A’; else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’;... else if (score >= 60) grade = ‘D’; else grade = ‘F’;

C++ Statements Note that a Statement can be either a single statement, or a compound statement: if (score > 100 || score < 0) { cerr << “Invalid score!\n”; exit(1); } else if (score >= 60) grade = ‘P’; else grade = ‘F’; If you need to select two or more statements, they must be wrapped in curley-braces to form a compound statement.

Using Selection Selection is useful anytime you want to execute a statement under particular circumstances. Example: Suppose we need a function that, given the number of a day of the week (1-7), computes its corresponding name (Sunday- Saturday)?

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

Coding 1 Such an algorithm can be coded using a multi-branch if: 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 “”; }

Drawback The multi-branch if has non-uniform execution time: Computing “Sunday” requires 1 comparisonComputing “Sunday” requires 1 comparison Computing “Tuesday” requires 2 comparisonsComputing “Tuesday” requires 2 comparisons Computing “Saturday” requires 7 comparisonsComputing “Saturday” requires 7 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 uniform.

A Solution The C++ switch statement provides an alternative: string DayName(int dayNumber) { switch (dayNumber) { case 1: return “Sunday”; case 2: return “Monday”; case 3: return “Tuesday”; case 4: return “Wednesday”; case 5: return “Thursday”; case 6: return “Friday”; case 7: return “Saturday”; default: cerr << “\n* DayName: invalid day number\n”; return “”; }

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

The switch Statement (ii) 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: 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 or statement. and each StatementList usually ends with a break or return statement.

Example Switch statements can use any integer-compatible type: double StraightPercentageCutOff(char letterGrade) { switch(letterGrade) { case ‘A’: return 90.0; case ‘B’: return 80.0; case ‘C’: return 70.0; case ‘D’: return 60.0; case ‘F’: return 0.0; default: cerr << “\n** Invalid letter grade: “ << letterGrade << “ received by StraightPercentageCutOff” << endl; exit(1); } They cannot be used with or values: They cannot be used with string or double values:

Another Restriction If (Variable == Constant 1 ) Statement 1 Else if (Variable == Constant 2 ) Statement 2... Else if (Variable == Constant N ) Statement N Else Statement N+1 To use the switch, the common algorithm pattern is To use the switch, the common algorithm pattern is: switch (Variable) { case Constant 1 : StatementList 1 case Constant 2 : StatementList 2... case Constant N : StatementList N default: StatementList N+1 }

Warning C++ switch statements exhibit drop-through behavior. 1. Expression is evaluated. 2. If Expression == ConstantValue i : Control jumps to the Statement after ConstantValue i. 3. Control continues within 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.

Example What will the following function display, if the value of is 3? What will the following function display, if the value of dayNumber is 3? 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; } Output: Output: TuesdayWednesdayThursdayFridaySaturdayError!

Solution To avoid the “drop-though” behavior, we need to add a statement at the end of each case: To avoid the “drop-though” behavior, we need to add a break 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 == 3: Output when dayNumber == 3: Tuesday

Difficulty There are other operations that are difficult to implement, using just sequential execution. Example: Let’s write a program to read in a sequence of test scores, and display their average and a corresponding pass/fail grade.

Repetitive Execution Finally, there are situations where solving a problem requires that a statement be repeated, with the repetition being controlled by a condition: for (InitializerExpr; LoopCondition; IncrementExpr) Statement The C++ for statement is a statement for eliciting repetitive execution of a statement, allowing a program to repeat the execution of Statement.

The for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement Statement will be executed so long as LoopCondition is true. InitializerExpr LoopCondition Statement IncrementExpr F T Statement is often called the body of the loop.

The for Loop for (InitializerExpr; LoopCondition; IncrementExpr) Statement Each execution of LoopCondition, Statement, IncrementExpr is called one repetition or iteration of the loop. InitializerExpr LoopCondition Statement IncrementExpr F T

The for Loop 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.

Counting The “normal” use of the for loop is to count: for (int count = 1; count <= limit; count++) cout << count << endl; Output (suppose limit == 7):

Nested Loops Loops can also be nested: for (int val1 = 1; val1 <= limit1; val1++) for (int val2 = 1; val2 <= limit2; val2++) cout << val1 << ‘*’ val2 “ = “ << val1 * val2 << endl; 1*1 = 1 1*2 = 2 1*3 = 3 2*1 = 2 2*2 = 4 2*3 = 6 Output (suppose limit1 == 2, limit2 == 3):

Counting Loops As we have indicated, the for loop is normally used to count through a range of values: for (int count = first; count <= last; count++) Statement Such a loop will count from first to last, executing Statement once for each value in the range first..last.

Noncounting Loops One of the quirks of the C++ for loop is that 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.

The forever Loop We call such a statement the forever loop: Pattern: for (;;) { StatementList 1 if (ExitCondition) break; StatementList 2 } When the if statement is evaluated and ExitCondition is true, the statement will execute, terminating the repetition. When the if statement is evaluated and ExitCondition is true, the break statement will execute, terminating the repetition.

Forever Behavior for (;;) { StatementList 1 if (ExitCondition) break; StatementList 2 } StatementList 1 ExitCondition StatementList 2 T F Note: we are guaranteed that StmtList1 will execute at least once, but StmtList2 may not execute...

Input Loops The forever loop is ideal for reading a list of values whose 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 }

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:

Error Handling A forever loop is also useful for fool-proof input. Pattern: for (;;) { Prompt for value Read value if (value is valid) break; Display error message } This is good because control will only leave the loop if/when the user enters a valid value.

Example double GetValidDouble(string prompt, double firstValid, double lastValid) { double number; for (;;) { cout << prompt; cin >> number; if (cin.good()) if (number >= firstValid && number <= lastValid) return number; else cout << “\n** Invalid number!\n” << endl; else { cout << “\n** Non-numeric input!\n” << endl; cin.clear(); cin.ignore(80, ‘\n’); } Read a valid number:

Summary The C++ compound statement executes a block of statements sequentially. The C++ if statement permits a statement to be executed selectively, based on a condition. The C++ for statement permits a statement to be executed repeatedly, based on a condition.