• No results found

Chapter 5. Selection 5-1

N/A
N/A
Protected

Academic year: 2021

Share "Chapter 5. Selection 5-1"

Copied!
20
0
0

Loading.... (view fulltext now)

Full text

(1)

Chapter 5

Selection

(2)

5-2

Selection (Decision)

The second control logic structure is selection:

Selection – Choosing between two or more alternative actions.

Selection statements alter the sequential flow of instructions in a program. This is done using selection statements. When we make the computer choose between two alternatives we will define one of the alternatives as begin true and the other as being false. This choice will be made using a

boolean expression.

Boolean Expression – an expression that evaluates to either true or false

When boolean expressions are formed they must set up a relationship between items in the expression. This relationship is set up using a set of operators called the relational operators.

Relational Operators: == (equal) < (less than) > (greater than)

<= (less than or equal) >= (greater than or equal) != (not equal)

NOTE: The assignment operator is (=) but the relational operator is(= =). In other words, if you are assigning a value to a variable, use (=) but if you are asking whether two things are equal, use (= =).

(3)

Comparing Floating Point Numbers

It is common to use numeric values in decision statements. Due to the way floating point numbers are stored in memory, do not compare two floating point values for equality. Floating point numbers must be rounded when they are stored in memory and rarely evaluate to be exactly the same. What we want to do is check to see if they are close enough to equal for us to call them equal. One easy method for doing this is to compare the absolute value of the difference of the numbers with some very small epsilon value. Given the following

const float EPSILON = 0.00001; float val1, val2;

if (fabs(val1 - val2) < EPSILON) {

cout << "values are equal"; }

fabs is a C++ library function that returns the absolute value of a floating

(4)

5-4

Examples of boolean expressions: Expression Result 5 == 5 TRUE ‘a’ < ‘c’ TRUE 4 + 3 > 10 FALSE 10 != 20 TRUE 6 <= 6 TRUE 5 >= 9 FALSE ‘A’ < ‘Z’ TRUE

‘a’ < ‘Z’ FALSE (WHY?)

Given two variables n1 and n2, assume n1 contains 5 and n2 contains 3. Evaluate each of the following boolean expressions:

n1 + 3 != n2 + 5 n1 * 2 <= n2 * 2 n1 >= n2

n2 <= n1

n2 + n1 + 3 == n1 + 6

The precedence order when the relational operators are added is as follows: * / %

+

-< -<= > >= == != =

(5)

The C++ If-Then and If-Then-Else Statements

The use of the If-Then and If-Then-Else statements in a program allows the programmer to include all possible options in the program code and the computer to select the appropriate option during program execution. Flowchart for the If-Then statement

boolean T

expression F

statement

The boolean expression is evaluated and if it evaluates to TRUE the statement inside the If is executed and the program continues to the next executable statement. If the expression evaluates to FALSE, the statement inside the If is ignored and the program continues with the next executable statement.

GENERAL FORM of the If-Then statement: if (boolean expression)

{

statement; }

(6)

5-6

T hours <= 40

output “No overtime” F

if (hours <= 40) {

cout << “No overtime” << endl; }

cout << “Continue” << endl;

Given a value of 25 in the location hours, the program would output No overtime

Continue

If location hours contained the value 50, the program would output Continue

(7)

Nested If-Then Statements

A nested If-Then is an If-Then that contains another If-Then within it. Suppose we wanted to identify 18 year old males. We could first determine whether the age requirement was met and if so, check to see whether the individual is a male. Outer If age == 18 T T Inner If F sex == ‘M’

output “The Marine Corps is

F looking for a few good men.”

if (age == 18) {

if (sex == ‘M’) {

(8)

5-8

The If-Then-Else Statement

In the If-Then statement a condition was evaluated and if the condition was true, an instruction was executed and the program continued on, if the condition was false, the program simply continued on. The If-Then-Else statement assures that some action will take place before the program continues. If the condition is true then do this else do that.

GENERAL FORM If-Then-Else Statement if (Expression) { statement 1; } else { statement 2; }

Flowchart for If-Then-Else

F

boolean T expression

(9)

Example:

F T

hours <= 40

output “overtime due” output “no overtime”

C++ code:

if (hours <= 40) {

cout << “no overtime”; }

else {

cout << “overtime due”; }

It is possible to “nest” If-Then-Else statements just as we did with If-Then statements.

(10)

5-10

If-Then-Else Exercise

1.) Draw the flowchart for a program that will receive three integers from the user. Your program is to output the largest of the three. We will assume that the three values are not equal. KEEP THIS AS AN EXAMPLE OF THE CORRECT FLOWCHART STYLE FOR NESTED IF/ELSE STATEMENTS.

(11)

The Conditional Operator

The conditional operator is a “shortcut” method that may be used to create

simple if/else expressions.

GENERAL FORM:

Expression ? expression : expression;

Example:

overTime = hrsWkd > 40 ? (hrsWkd-40)*rate*1.5 : 0.0;

The part of the conditional expression that precedes the ? is the expression to be tested (like the expression in parentheses in an if statement). If the

expression is true, the statement between the ? and : is executed otherwise the expression after the : is executed. The statement above could replace the

block if shown below.

if (hrsWkd > 40)

overTime = hrsWkd-40) * rate * 1.5; else

overTime = 0.0; or even

(12)

5-12

Logical/Boolean Operators and Expressions

George Boole’s The Mathematical Analysis of Logic was published in 1847. The formal axioms of logic were set forth in this book and the field of

symbolic logic was built. This logic eventually formed the basis for the development of digital computers. We will use the boolean operators to form complex decision statements.

NOT ! unary operator AND && binary operator OR || binary operator

By using these operators in conjunction with the relational operators, more complex expressions may be formed.

NOT (!) precedes a single expression and gives its opposite as the result. hrsWkd <= 40

is equivalent to !(hrsWkd > 40)

(13)

AND (&&) combines two logical expressions and requires that both expressions be TRUE for the entire expression to be TRUE

num1 <= 10 && num1 != 5

The value of num1 would need to be less than or equal to 10 and also not equal to 5 for this expression to be TRUE

OR (||) combines two logical expressions and states that if either or both of the expressions are TRUE, the entire expression is TRUE

num1 <1 || num1 > 10

If the value of num1 is not in the range 1-10 this expression evaluates to TRUE

Rewrite the following expressions: !(num1 == num2)

!(num1 == num2 || num1 == num3) !(num1 == num2 && num3 > num4)

(14)

5-14

In math books the notation 5 < x < 15

is common. It means that x is between 5 and 15. While the expression is legal in C++ the result is unexpected. What is the result and why?

(15)

Short-Circuit Evaluation: Evaluation of a logical expression in

left-to-right order with evaluation stopping as soon as the final truth can be determined.

When AND is used in an expression, the computer stops evaluation as soon as a FALSE condition is found. When OR is used in an expression,

evaluation can stop as soon as the first TRUE condition is found. Some languages use full evaluation of logical expressions where both

subexpressions are evaluated before the && or || operator is applied.

Precedence of Operators ( ) Highest ++ --! * / % + -< -<= > >= == != && || = Lowest

(16)

5-16

Exercises

1 Given the following values for variables a, b and c:

a = TRUE b = FALSE c = TRUE

evaluate each of the following expressions a) a && b || a && c

b) !(a && c) || b

c) !a || c && b

2. Rewrite the following expressions so they would be valid in C++. a) a, b and c are all less than 10

b) a > b >= c

c) a does not equal either b or c

(17)

Boolean Expressions Programming Exercise

A military academy accepts candidates according to the following height and weight requirements.

Gender Min. Height Max. Height Min. Weight Max. Weight

Male 62 in. 78 in. 130 lbs. 250 lbs.

Female 60 in. 72 in. 110 lbs. 185 lbs.

Design a program that accepts as input the gender, height and weight of a candidate. Check to see if the candidate meets the height requirements and store the result in a bool variable called heightOk. Next check the weight requirements and store the result in a bool variable called weightOk. Using these results, determine whether the candidate was accepted, rejected for height only, rejected for weight only or rejected for both height and weight. Output an appropriate message for each possible outcome.

(18)

5-18

Multi-way Selection

The switch statement in C++ provides a way to eliminate some nested if structures. The general form for the switch statement is

switch (IntegralExpression) { SwitchLabel
statement; . . }

The general form for the SwitchLabel is

case ConstantExpression: default:

where

‱ The switch expression is the expression whose value determines which label is selected. It cannot be a floating point expression.

‱ The SwitchLabel is either a case label or a default label. In the case label, the ConstantExpression must be an integral literal or a named constant.

‱ Each case constant may appear only once in the statement.

‱ The switch expression is evaluated and if the value matches one of the constants in the case label, control branches to to the statement following the label. From there it proceeds sequentially until the end of the switch statement or until a break is

encountered.

‱ If there is no matching label for the expression, it looks for a default label and if found, executes the statement following the label. If no default label is present, control transfers to the statement following the end of the switch statement.

(19)

Example:

classCode

‘F’ ‘S’ ‘J’ ‘R’ default

Freshman Sophomore Junior Senior Invalid

switch (classCode) {

case ‘F’ : cout << “You are a freshman”; break;

case ‘S’ : cout << “You are a sophomore”; break;

case ‘J’ : cout << “You are a junior”; break;

case ‘R’ : cout << “You are a senior”; break;

default : cout << “You entered an invalid code”; break; // not necessary but a good habit }

(20)

5-20

The fact that without the break statement, the program “follows through” can be helpful in some situations. Suppose we wanted to allow for lower case input as well.

switch (classCode) {

case ‘F’ :

case ‘f’ : cout << “You are a freshman”; break;

case ‘S’ :

case ‘s’ : cout << “You are a sophomore”; break;

etc.

Switch Exercises:

1. Flowchart a code segment that reads a letter grade from the keyboard and prints “good work” for A and B students, “average work” for C students, and “poor work” for D and F students. Draw this flowchart as a nested if.

2 Write the C++ code to match the flowchart from #1.

3 Draw the flowchart to convert the nested if into a switch statement. 4 Write the C++ code for the flowchart from #3.

References

Related documents

This paper provides outcomes from an evaluation of a federally funded program combining HIV prevention services with an integrated mental health and substance abuse treatment

WIP MEMORY CARD Saffiano bonded leather bookmark with page marker and pocket for 4GB USB key or credit card... WIP MEMORY KEY Saffiano bonded leather bookmark with 4GB

To that end, the Open Travel Alliance (OTA) was formed in 1998 and now has a global membership of over 150 travel companies from suppliers, such as airlines, hotels, car rental, rail,

Total and exploitable biomass for both shell height:meat weight relationships and levels of assumed gear efficiency are shown in Tables 7-8 (total biomass for the CFTDD is

Using the factor procedure the three factors were constructed for future analysis: an operational factor (HIP95, KNEE95, HIP96, KNEE96, and FEMUR96), a size factor (BEDS,

For establishments that reported or imputed occupational employment totals but did not report an employment distribution across the wage intervals, a variation of mean imputation

Meer dan iets anders heeft dit het uniforme beeld van een algemene derde eeuwse crisis van bijna honderd jaar bijgesteld en aangetoond dat crisis – zeker tot halverwege de eeuw –

Applying this framework to the Norwegian Offshore Cluster changes the logic of industrial development from an engineering logic to a knowledge logic, implying that