Presentation is loading. Please wait.

Presentation is loading. Please wait.

7-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8.

Similar presentations


Presentation on theme: "7-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8."— Presentation transcript:

1 7-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8 Presentation Copyright 1999, Franklin, Beedle & Associates Students who purchase and instructors who adopt Computing Fundamentals with C++, Object-Oriented Programming and Design by Rick Mercer are welcome to use this presentation as long as this copyright notice remains intact.

2 7-2 Chapter 7 Selections  In this chapter we study algorithmic patterns that allow alternatives to straight sequential processing. In particular:  Guarded Action  execute an action only under certain conditions  Alternative Action  choose one action or another  Multiple Selection  choose from more than two sets of actions

3 7-3 Chapter Objectives: Part I  Recognize when to use Guarded Action  Implement Guarded Action pattern with if  Use relational (<) and equality (==) operators  Create and evaluate expressions with logical operators not !, and &&, or ||  Use bool  Understand the Alternative Action Pattern  Implement Alternative Action with if…else –Exercises –Programming Projects

4 7-4 Chapter Objectives: Part II  Choose one action from many (more than 2) using the if…else and switch statements  Solve problems using multiple selection  Exercises  Programming Projects Note: There are two sets of exercises and programming projects

5 7-5 Why do we need selection?  Programs must often anticipate a variety of situations  Consider an Automated Teller Machine:  ATMs must serve valid bank customers. They must also reject invalid PINs.  The code that controls an ATM must permit these different requests.  Software developers must implement code that anticipates all possible transactions.

6 7-6 7.1 Selective Control  Programs often contain statements that may not always execute  Sometimes a statement may execute and other certain conditions it may not  Reject invalid PIN entries at an ATM  We say an action is guarded from executing

7 7-7 7.1.1 The Guarded Action Pattern Pattern: Guarded Action Problem: Execute an action only under certain conditions General if( logical-expression ) Form: true-part Code if(aStudent.GPA() >= 3.5) Example: deansList.push_back(aStudent);

8 7-8 7.1.2 The if statement  The if is the first statement that alters strict sequential control. General form of the if: if ( logical-expression ) if ( logical-expression ) true-part ; true-part ;  logical-expression: any expression that evaluates to nonzero (true) or zero (false)  In C++, almost everything is true or false

9 7-9 What happens when an if statement executes?  After the logical expression of the if statement evaluates, the true-part executes only if the logical expression is true. logical expression False statement -1 statement-n True Part

10 7-10 Example if statement double hours = 38.0; double hours = 38.0; // Add 1.5 hours for hours over 40.0 (overtime) // Add 1.5 hours for hours over 40.0 (overtime) if(hours > 40.0) if(hours > 40.0) hours = 40.0 + 1.5 * (hours - 40.0); hours = 40.0 + 1.5 * (hours - 40.0);  Write last value of hours when it starts as: double hours = 38.0; ____________ double hours = 38.0; ____________ double hours = 40.0; ____________ double hours = 40.0; ____________ double hours = 42.0; ____________ double hours = 42.0; ____________ Optional Demo awards.cpp demontrates the variety of program execution when the if statement is used

11 7-11 Another way  The if statement could also be written with a block as the true part: here it is not necessary if(hours > 40.0) if(hours > 40.0) { hours = 40.0 + 1.5 * (hours - 40.0); hours = 40.0 + 1.5 * (hours - 40.0); }  Sometimes the block is required consider using { } if(hours > 40.0) { regularHours = 40.0; regularHours = 40.0; overtimeHours = hours - 40.0; overtimeHours = hours - 40.0; }

12 7-12 7.2 Logical expressions with Relational Operators  Logical expressions often use these relational operators:

13 7-13 Logical Expressions  Examples (Write T for True, or F for False): int n1 = 78; int n1 = 78; int n2 = 80; int n2 = 80; n1 < n2 // _____ n1 < n2 // _____ n1 >= n2 // _____ n1 >= n2 // _____ (n1 + 35) > n2 // _____ (n1 + 35) > n2 // _____ fabs(n1-n2) <= 0.00001// _____ fabs(n1-n2) <= 0.00001// _____ n1 == n2 // _____ n1 == n2 // _____ n1 != n2 // _____ n1 != n2 // _____

14 7-14 More Logical Expressions (with strings this time)  Examples (Write T for True, or F for False): string s1 = "Pierre"; string s1 = "Pierre"; string s2 = "Winder"; string s2 = "Winder"; s1 < s2 // _____ s1 < s2 // _____ s1 > s2 // _____ s1 > s2 // _____ s1 == s2 // _____ s1 == s2 // _____ s1 != s2 // _____ s1 != s2 // _____ s1 > "Pierrey" // _____ s1 > "Pierrey" // _____ s2 < "Windy" // _____ s2 < "Windy" // _____

15 7-15 Using relational operators in if statements double x = 59.0; double x = 59.0; if(x >= 60.0) if(x >= 60.0) { cout << "passing"; cout << "passing"; } if(x < 60.0) if(x < 60.0) { cout << "below 60.0"; cout << "below 60.0"; } double x = 59.0; ? __________________________ ? double x = 59.0; ? __________________________ ? double x = 60.0; ? __________________________ ? double x = 60.0; ? __________________________ ? double x = 61.0; ? __________________________ ? double x = 61.0; ? __________________________ ?

16 7-16 Programming Tip:  Using = for == is a common mistake. For example the following two statements are legal, but... int x = 25; int x = 25; // Because assignment statements evaluate to the // Because assignment statements evaluate to the // expression on the right of =, x = 1 is always // expression on the right of =, x = 1 is always // 1, which is nonzero, which is true: // 1, which is nonzero, which is true: if(x = 1) // should be (x == 1) if(x = 1) // should be (x == 1) cout << "I'm always displayed"; cout << "I'm always displayed";  So consider putting the constant first if(1 = x) // this is an obvious compiletime error if(1 = x) // this is an obvious compiletime error

17 7-17 7.3 The Alternative Action Pattern  Programs often contain statements that select between one set of actions or another  Examples  withdraw or deposit money  pass or fail the entrance requirements  This is the Alternative Action Pattern  choose between two alternate sets of actions

18 7-18 Alternative Action Pattern: Alternative Action Problem: Must choose one action from two alternatives Outline: if (true-or-false-condition is true) action-1 else action-2 if(finalGrade >= 60.0) Code if(finalGrade >= 60.0) cout << "passing" << endl; cout << "passing" << endl; else else cout << "failing" << endl; cout << "failing" << endl;

19 7-19 if-else General Form if ( logical-expression ) if ( logical-expression ) true-part ; true-part ; else else false-part ; false-part ;  When the logical expression evaluates to true, the true-part executes and the false-part is disregarded. When the logical expression is false, only the false- part executes.

20 7-20 7.3.1 The if...else statement  The if...else statement allows two alternate courses of action. logical expression False statement-1 statement-n statement-1 statement-n True False Part True Part

21 7-21 if...else Example if(miles > 24000) cout << "Tune-up " << miles-24000 << " miles overdue"; cout << "Tune-up " << miles-24000 << " miles overdue";else cout << "Tune-up due in " << 24000-miles << " miles"; cout << "Tune-up due in " << 24000-miles << " miles"; MilesOutput 30123____________________________ 2000____________________________ 24000____________________________ Demonstrate the variety of program execution for the three values shown above tuneup.cpp

22 7-22 7.4 The Block with Selection Structures { }  Again, the blocks may be used even when unecessary and again, consider always using them if(miles > 24000) if(miles > 24000) { cout<< "Tune-up " << miles-24000 << " miles overdue"; cout<< "Tune-up " << miles-24000 << " miles overdue"; } else else { cout<< "Tune-up due in " << 24000-miles << " miles"; cout<< "Tune-up due in " << 24000-miles << " miles"; }  Using curly braces all the time helps avoid difficult to detect errors

23 7-23 Sometimes blocks are necessary if(GPA >= 3.5) { // true-part contains more than one statement in this block cout << "Congratulations, you're on the Dean's List."<< endl; cout << "Congratulations, you're on the Dean's List."<< endl; margin = GPA - 3.5; margin = GPA - 3.5; cout << "You made it by " << margin << " points." << endl; cout << "You made it by " << margin << " points." << endl;}else { // false-part contains more than one statement in this block cout << "Sorry, you are not on the Dean's List." << endl; cout << "Sorry, you are not on the Dean's List." << endl; margin = 3.5 - GPA; margin = 3.5 - GPA; cout << "You missed it by " << margin << " points." << endl; cout << "You missed it by " << margin << " points." << endl;} totalMargin = totalMargin + margin;

24 7-24 7.4.1 the trouble in Forgetting { }  Failing to use { and } if(GPA >= 3.5) if(GPA >= 3.5) // The true-part is the first cout only // The true-part is the first cout only cout <<"Congrats, you're on the Dean's List. "; cout <<"Congrats, you're on the Dean's List. "; margin = GPA - 3.5; margin = GPA - 3.5; cout <<"You made it by " << margin << " points."; cout <<"You made it by " << margin << " points."; else >>> else >>>

25 7-25 7.4.1 the trouble in Forgetting { }  There are no compiletime errors next, but there is an intent error. else else cout << "Sorry, you're not on the Dean's List." << endl; cout << "Sorry, you're not on the Dean's List." << endl; margin = 3.5 - GPA; margin = 3.5 - GPA; cout << "You missed it by " << margin << " points."; cout << "You missed it by " << margin << " points.";  With the above false part, you could get this confusing output (when GPA = 3.9): Congrats, you're on the Dean's list. Congrats, you're on the Dean's list. You made it by 0.4 points. You made it by 0.4 points. You missed it by -0.4 points. You missed it by -0.4 points.

26 7-26 7.5 bool Objects  The standard bool class stores one of two values  true and false  A bool object stores the result of a logical expression: bool ready = false; bool ready = false; double hours = 4.5; double hours = 4.5; ready = hours >= 4.0; ready = hours >= 4.0; cout << ready << endl; // Displays 1 for true cout << ready << endl; // Displays 1 for true

27 7-27 bool Functions  It is common to have functions that return one of the bool values (true or false). bool odd(int n) { // post: return true if n is an odd integer return (n % 2) != 0; return (n % 2) != 0;} // Client code if( odd(j) ) j = j + 1; j = j + 1; // assert: j is an even integer

28 7-28 7.5.1 Boolean Operators  A logical operator (&& means AND) used in an if...else statement: if( (test >= 0) && (test = 0) && (test <= 100) ) cout << "Test in range"; cout << "Test in range"; else else cout << "**Warning--Test out of range"; cout << "**Warning--Test out of range";  The code describes whether or not test is in the range of 0 through 100 inclusive.

29 7-29 Truth Tables for Boolean Operators  Truth tables for the Logical (Boolean) operators !, ¦¦, &&

30 7-30 Using && in an expression  Assuming test == 97,  Is test within the range of 0 and 100 inclusive? ( (test >= 0) && (test = 0) && (test <= 100) ) ( ( 97 >= 0) && ( 97 = 0) && ( 97 <= 100) ) ( true && true ) ( true && true ) true true  Is test outside the range of 0 and 100 inclusive? ( (test 100) ) ( (test 100) ) ( ( 97 100) ) ( ( 97 100) ) ( false ¦¦ false ) ( false ¦¦ false ) false false  Evaluate both expressions when test == 101 ?__?

31 7-31 More Precedence Rules  The following slide summarizes all operators used in this textbook (we've seen 'em all)  Precedence: most operators are evaluated (grouped) in a left-to-right order: a / b / c / d is equivalent to (((a/b)/c)/d) a / b / c / d is equivalent to (((a/b)/c)/d)  Assignment operators group in a right-to-left order so the expression x = y = z = 0.0 is equivalent to (x=(y=(z=0.0))) x = y = z = 0.0 is equivalent to (x=(y=(z=0.0)))  Also note that standard C++ has the operators: not and or // we'll use ! && ||

32 7-32 Operators used in this book

33 7-33 Applying Operators and Precedence Rules  Use the precedence rules to evaluate the following expression: int j = 5; int k = 10; bool TorF; TorF = (j * (1 + k) > 55) ¦¦ (j + 5 k)  What is assigned to TorF _______?

34 7-34 7.5.3 The Boolean "or" || with a grid Object bool moverOnEdge(const grid & g) { // post: return true if the mover is on an edge // or false otherwise // or false otherwise return( g.row()==0 // on north edge? return( g.row()==0 // on north edge? || g.row()==g.nRows()-1 // on south edge? || g.row()==g.nRows()-1 // on south edge? || g.column()==0 // on west edge? || g.column()==0 // on west edge? || g.column()==g.nColumns()-1 ); // east? || g.column()==g.nColumns()-1 ); // east?} int main() { grid tarpit( 5, 10, 4, 4, east ); grid tarpit( 5, 10, 4, 4, east ); if( moverOnEdge(tarpit) ) if( moverOnEdge(tarpit) ) cout << "On edge" << endl; cout << "On edge" << endl; else else cout << "Not" << endl; cout << "Not" << endl; return 0; return 0;} Optional Demo: onedge.cpp

35 7-35 7.5.4 Short Circuit Boolean Evaluation  C++ logical expressions evaluate subexpressions in a left to right order  Sometimes the evaluation can stop early  This never evaluates sqrt of a negative number: if((x >= 0.0) && (sqrt(x) = 0.0) && (sqrt(x) <= 2.5)) //... //...  test>100 is not evaluated when test 100 is not evaluated when test<0 is true if(test 100) if(test 100) //... //...

36 7-36 7.6 A bool member function PREREQUISITE: Chapter 6  Consider changing bankAccount::withdraw so it only withdraw money if the balance is sufficient.  Also have it return true in this case  Have it return false when there are insufficient funds  First change heading in class bankAccount bool withdraw(double withdrawalAmount); // was void bool withdraw(double withdrawalAmount); // was void

37 7-37 a bool member function continued a bool member function continued  Also change implementation in baccount.cpp bool bankAccount::withdraw(double withdrawalAmount) bool bankAccount::withdraw(double withdrawalAmount) { // post: return true if withdrawal was successful { // post: return true if withdrawal was successful // or false with insufficient funds // or false with insufficient funds bool result = false; bool result = false; if(my_balance >= withdrawalAmount) if(my_balance >= withdrawalAmount) { my_balance = my_balance - withdrawalAmount; my_balance = my_balance - withdrawalAmount; result = true; result = true; } return result; return result; }

38 7-38 7.7 Multiple Selection  Nested logic:  one control structure contains another similar control structure  an if...else inside another if...else  allows selections from 3 or more alternatives  We must often select one alternative from many

39 7-39

40 7-40 Example of Multiple Selection nested if...else if(GPA < 3.5) if(GPA < 3.5) cout << "Try harder" << endl; cout << "Try harder" << endl; else else if(GPA < 4.0) if(GPA < 4.0) cout << "Dean's List" << endl; cout << "Dean's List" << endl; else else cout << "President's list" << endl; cout << "President's list" << endl; GPAOutput: 3.0__________________ 3.6__________________ 4.0__________________ The false part is another if...else

41 7-41 Active Learning  Given the scale below, Complete the function (next slide) with a nested if..else to display the appropriate message: Value of C°Output C >= 34 Hot 20 <= C < 34 Warm 12 <= C < 20 Mild 0 <= C < 12 Cold C < 0Freezing

42 7-42 string weather(int C) { // post: return appropriate message string result; string result; if( C >= 34 ) if( C >= 34 ) result = "Hot"; result = "Hot"; else if(C >= 20) else if(C >= 20) result ="Warm"; result ="Warm"; return result; return result;}

43 7-43 7.7.2 Multiple Returns  It's possible to have multiple return statements in a function terminate when the first return executes string letterGrade(double percentage) string letterGrade(double percentage) { if(percentage >= 90) if(percentage >= 90) return "A"; return "A"; if(percentage >= 80) if(percentage >= 80) return "B"; return "B"; if(percentage >= 70) if(percentage >= 70) return "C"; return "C"; if(percentage >= 60) if(percentage >= 60) return "D"; return "D"; return "F"; // return F when percentage < 0 return "F"; // return F when percentage < 0 }

44 7-44 7.8 Testing Multiple Selection  It is often difficult and unnecessary to test every possible value imagine all those doubles 0.1, 0.001, 0.0001,...  Testing our code in "most" branches can prove dangerously inadequate  Each branch through the multiple selection should be tested.

45 7-45 Perform Branch Coverage Test  To correctly perform branch coverage testing we need to do the following:  Establish a set of data that ensures all paths will execute the statements after the logical expressions  Execute the code call the function with the nested logic for all selected data values  Observe that the code behaves correctly for all data compare program output with expected results  This is glass box testing when you look at the code

46 7-46 7.8.1 Boundary Testing  Boundary testing involves executing the code using the boundary (cutoff) values  What grade would you receive with a percentage of 90 using this code if( percentage > 90 ) if( percentage > 90 ) grade = "A"; grade = "A"; else if( percentage >= 80 ) else if( percentage >= 80 ) grade = "B"; grade = "B"; Optional Demo b&btest.cpp Perform branch and boundary testing with the temperature example

47 7-47 7.9 The switch Statement (General form) switch ( switch-expression ) { case value-1 : case value-1 : statement(s)-1 statement(s)-1 break ;... // many cases are allowed break ;... // many cases are allowed case value-n : case value-n : statement(s)-n statement(s)-n break ; break ; default : default : default-statement(s) default-statement(s)}

48 7-48 Switch control  When a switch statement is encountered:  the switch-expression is evaluated. This value is compared to each case value until switch-expression == case value. All statements after the colon : are executed.  It is important to include the break statement  The switch expression must evaluate to one of C++'s integral types  int, char, or enum

49 7-49 7.9.1 char Objects  A char object stores 1 character 'A' 'x' 'c' '?' ' ' '1' '.'  or 1 escape sequence

50 7-50 Example switch statement: char option = '?'; cout << "Enter W)ithdraw D)eposit B)alances: "; cin >> option; switch(option) { case 'W': case 'W': cout << "Withdraw" << endl; cout << "Withdraw" << endl; break; break; case 'D': case 'D': cout << "Deposit" << endl; cout << "Deposit" << endl; break; break; case 'B': case 'B': cout << "Balance" << endl; cout << "Balance" << endl; break; break; default: default: cout << "Invalid" << endl; cout << "Invalid" << endl; } // end switch

51 7-51 Trace the previous switch  Show output when option == '?'____________? option == '?'____________? option == 'W'____________? option == 'W'____________? option == 'B'____________? option == 'B'____________? option == 'A'____________? option == 'A'____________? option == 'Q'____________? option == 'Q'____________?


Download ppt "7-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8."

Similar presentations


Ads by Google