510 likes | 663 Views
Selections. In this lesson we study algorithmic patterns that allow alternatives to straight sequential processing. In particular:Guarded Actionexecute an action only under certain conditionsAlternative Actionchoose one action or anotherMultiple Selectionchoose from more than two sets of actio
E N D
2. Selections In this lesson 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. Lesson Goals: 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. Lesson Goals: 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. 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. Selective Control Programs often contain statements that may not always execute
Sometimes a statement may execute and under certain conditions it may not
Reject invalid PIN entries at an ATM
We say an action is guarded from executing
7. The Guarded Action Pattern
8. The if statement The if is the first statement that alters strict sequential control. General form of the if:
if ( logical-expression )
true-part ;
logical-expression: any expression that evaluates to nonzero (true) or zero (false).
In C++, almost everything is true or false.
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.
10. Example if statement double hours = 38.0;
// Add 1.5 hours for hours over 40.0 (overtime)
if(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 = 40.0; ____________
double hours = 42.0; ____________
Optional Demo awards.cpp demontrates the variety of program execution when the if statement is used
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)
{
hours = 40.0 + 1.5 * (hours - 40.0);
}
Sometimes the block is required consider using { }
if(hours > 40.0)
{
regularHours = 40.0;
overtimeHours = hours - 40.0;
}
12. Logical expressions with Relational Operators Logical expressions often use these relational operators:
13. Logical Expressions Examples (Write T for True, or F for False):
int n1 = 78;
int n2 = 80;
n1 < n2 // _____
n1 >= n2 // _____
(n1 + 35) > n2 // _____
fabs(n1-n2) <= 0.00001 // _____
n1 == n2 // _____
n1 != n2 // _____
14. More Logical Expressions (with strings this time) Examples (Write T for True, or F for False):
string s1 = "Pierre";
string s2 = "Winder";
s1 < s2 // _____
s1 > s2 // _____
s1 == s2 // _____
s1 != s2 // _____
s1 > "Pierrey" // _____
s2 < "Windy" // _____
15. Using relational operators in if statements double x = 59.0;
if(x >= 60.0)
{
cout << "passing";
}
if(x < 60.0)
{
cout << "below 60.0";
}
double x = 59.0; ? __________________________ ?
double x = 60.0; ? __________________________ ?
double x = 61.0; ? __________________________ ?
16. Programming Tip: Using = for == is a common mistake. For example the following statements are legal:
int x = 25;
// Because assignment statements evaluate to the
// expression on the right of =, x = 1 is always
// 1, which is nonzero, which is true:
if(x = 1) // should be (x == 1)
cout << "I'm always displayed";
So consider putting the constant first
if(1 = x) // this is an obvious compiletime error
17. 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. Alternative Action
19. if-else General Form if ( logical-expression )
true-part ;
else
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. The if...else statement The if...else statement allows two alternate courses of action.
21. if...else Example if(miles > 24000)
cout << "Tune-up " << miles-24000 << " miles overdue";
else
cout << "Tune-up due in " << 24000-miles << " miles";
Miles Output
30123 ____________________________
2000 ____________________________
24000 ____________________________
Demonstrate the variety of program execution for the three values shown above tuneup.cpp
22. The Block with Slection Structures { } Again, the blocks may be used even when unecessary and again, consider always using them
if(miles > 24000)
{
cout<< "Tune-up " << miles-24000 << " miles overdue";
}
else
{
cout<< "Tune-up due in " << 24000-miles << " miles";
}
Using curly braces all the time helps avoid difficult to detect errors
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;
margin = GPA - 3.5;
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;
margin = 3.5 - GPA;
cout << "You missed it by " << margin << " points." << endl;
}
totalMargin = totalMargin + margin;
24. The trouble in Forgetting { } Failing to use { and }
if(GPA >= 3.5)
// The true-part is the first cout only
cout <<"Congrats, you're on the Dean's List. ";
margin = GPA - 3.5;
cout <<"You made it by " << margin << " points.";
else <<<< Error >>>>
25. The trouble in Forgetting { } There are no compiletime errors next, but there is an intent error.
else
cout << "Sorry, you're not on the Dean's List." << endl;
margin = 3.5 - GPA ;
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.
You made it by 0.4 points.
You missed it by -0.4 points.
26. 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;
double hours = 4.5;
ready = hours >= 4.0;
cout << ready << endl; // Displays 1 for true
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;
}
// Client code
if( odd(j) )
j = j + 1;
// assert: j is an even integer
28. Boolean Operators A logical operator (&& means AND) used in an if...else statement:
if( (test >= 0) && (test <= 100) )
cout << "Test in range";
else
cout << "**Warning--Test out of range";
The code describes whether or not test is in the range of 0 through 100 inclusive.
29. Truth Tables for Boolean Operators Truth tables for the Logical (Boolean) operators !, ¦¦, &&
30. Using && in an expression Assuming test == 97,
Is test within the range of 0 and 100 inclusive?
( (test >= 0) && (test <= 100) )
( ( 97 >= 0) && ( 97 <= 100) )
( true && true )
true
Is test outside the range of 0 and 100 inclusive?
( (test < 0) ¦¦ (test > 100) )
( ( 97 < 0) ¦¦ ( 97 > 100) )
( false ¦¦ false )
false
Evaluate both expressions when test == 101 ?__?
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)
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)))
Also note that standard C++ has the operators:
not and or // we'll use ! && ||
32. Operators used in this book
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) && (j>k)
What is assigned to TorF_______?
34. 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
return( g.row()==0 // on north edge?
|| g.row()==g.nRows()-1 // on south edge?
|| g.column()==0 // on west edge?
|| g.column()==g.nColumns()-1 ); // east?
}
int main()
{
grid tarpit( 5, 10, 4, 4, east );
if( moverOnEdge(tarpit) )
cout << "On edge" << endl;
else
cout << "Not" << endl;
return 0;
}
35. 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) <= 2.5))
// ...
test>100 is not evaluated when test<0 is true
if(test < 0 || test > 100)
// ...
36. A bool member functionPREREQUISITE: 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
37. a bool member function continued Also change implementation in baccount.cpp
bool bankAccount::withdraw(double withdrawalAmount)
{ // post: return true if withdrawal was successful
// or false with insufficient funds
bool result = false;
if(my_balance >= withdrawalAmount)
{
my_balance = my_balance - withdrawalAmount;
result = true;
}
return result;
}
38. 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.
40. Example of Multiple Selection nested if...else if(GPA < 3.5)
cout << "Try harder" << endl;
else
if(GPA < 4.0)
cout << "Dean's List" << endl;
else
cout << "President's list" << endl;
GPA Output:
3.0 __________________
3.6 __________________
4.0 __________________
41. Another Example Given the following scale,
Value of C° Output
C >= 34 Hot
20 <= C < 34 Warm
12 <= C < 20 Mild
0 <= C < 12 Cold
C < 0 Freezing
Complete the following function with a nested if..else to display the appropriate message:
42. string weather(int C)
{ // post: return appropriate message
string result;
if( C >= 34 )
result = "Hot";
else if(C >= 20)
result ="Warm";
return result;
}
43. Multiple Returns It's possible to have multiple return state-ments in a function terminate when the first return executes
string letterGrade(double percentage)
{
if(percentage >= 90)
return "A";
if(percentage >= 80)
return "B";
if(percentage >= 70)
return "C";
if(percentage >= 60)
return "D";
if(percentage >= 0) // Change the last if to return "F";
return "F"; // WRONG when percentage < 0
}
44. Testing Multiple Selection It is often difficult and unecesssary to test every possible value imagine all the doubles
Testing our code in "most" branches can prove dangerously inadequate.
Each branch through the multiple selection should be tested.
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. 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 )
grade = "A";
else if( percentage >= 80 )
grade = "B";
Optional Demo b&btest.cpp
Perform branch and boundary testing with the temperature example
47. The switch Statement (General form) switch ( switch-expression )
{
case value-1 :
statement(s)-1
break ; ... // many cases are allowed
case value-n :
statement(s)-n
break ;
default :
default-statement(s)
}
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. char Objects A char object stores 1 character
'A' 'x' 'c' '?' ' ' '1' '.'
or 1 escape sequence
50. Example switch statement: char option = '?';
cout << "Enter W)ithdraw D)eposit B)alances: ";
cin >> option;
switch(option) {
case 'W':
cout << "Withdraw" << endl;
break;
case 'D':
cout << "Deposit" << endl;
break;
case 'B':
cout << "Balance" << endl;
break;
default:
cout << "Invalid" << endl;
} // end switch
51. Trace the previous switch Show output when
option == '?' ____________?
option == 'W' ____________?
option == 'B' ____________?
option == 'A' ____________?
option == 'Q' ____________?