This action might not be possible to undo. Are you sure you want to continue?

5-1

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 (= =).

5-2

One easy method for doing this is to compare the absolute value of the difference of the numbers with some very small epsilon value. } fabs is a C++ library function that returns the absolute value of a floating point expression. What we want to do is check to see if they are close enough to equal for us to call them equal. Due to the way floating point numbers are stored in memory. if (fabs(val1 . Given the following const float EPSILON = 0.00001. do not compare two floating point values for equality. float val1.val2) < EPSILON) { cout << "values are equal".Comparing Floating Point Numbers It is common to use numeric values in decision statements. val2. 5-3 . Floating point numbers must be rounded when they are stored in memory and rarely evaluate to be exactly the same.

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: * / % + < <= > >= == != = Parentheses may be used to alter the order of evaluation.

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. If the expression evaluates to FALSE. } 5-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 expression F T 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.

Given a value of 25 in the location hours. } cout << “Continue” << endl. the program would output Continue 5-6 . the program would output No overtime Continue If location hours contained the value 50.T hours <= 40 output “No overtime” F if (hours <= 40) { cout << “No overtime” << endl.

” if (age == 18) { if (sex == ‘M’) { cout << “The Marine Corps is looking for a few good men. 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.”.Nested If-Then Statements A nested If-Then is an If-Then that contains another If-Then within it. We could first determine whether the age requirement was met and if so. Suppose we wanted to identify 18 year old males. } } 5-7 .

The If-Then-Else Statement In the If-Then statement a condition was evaluated and if the condition was true. } Flowchart for If-Then-Else F boolean expression statement 2 T statement 1 5-8 . an instruction was executed and the program continued on. the program simply continued on. } else { statement 2. 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. if the condition was false. GENERAL FORM If-Then-Else Statement if (Expression) { statement 1.

5-9 . } It is possible to “nest” If-Then-Else statements just as we did with If-Then statements. } else { cout << “overtime due”.Example: F hours <= 40 T output “overtime due” output “no overtime” C++ code: if (hours <= 40) { cout << “no overtime”.

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

if (hrsWkd > 40) overTime = hrsWkd-40) * rate * 1. or even cout << “Overtime is “ << (hrsWkd > 40 ? (hrsWkd-40)* rate * 1.The Conditional Operator The conditional operator is a “shortcut” method that may be used to create simple if/else expressions.0). Example: overTime = hrsWkd > 40 ? (hrsWkd-40)*rate*1. 5-11 .0. GENERAL FORM: Expression ? expression : expression. The statement above could replace the block if shown below.5 : 0.0. else overTime = 0. If the expression is true.5 : 0.5. The part of the conditional expression that precedes the ? is the expression to be tested (like the expression in parentheses in an if statement). the statement between the ? and : is executed otherwise the expression after the : is executed.

The formal axioms of logic were set forth in this book and the field of symbolic logic was built. NOT (!) precedes a single expression and gives its opposite as the result. hrsWkd <= 40 is equivalent to !(hrsWkd > 40) 5-12 . more complex expressions may be formed. NOT AND OR ! && || unary operator binary operator binary operator By using these operators in conjunction with the relational operators.Logical/Boolean Operators and Expressions George Boole’s The Mathematical Analysis of Logic was published in 1847. This logic eventually formed the basis for the development of digital computers. We will use the boolean operators to form complex decision statements.

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) 5-13 .

What is the result and why? How should the expression be written? 5-14 .In math books the notation 5 < x < 15 is common. While the expression is legal in C++ the result is unexpected. It means that x is between 5 and 15.

Some languages use full evaluation of logical expressions where both subexpressions are evaluated before the && or || operator is applied. evaluation can stop as soon as the first TRUE condition is found. When AND is used in an expression. Precedence of Operators () ++ -! * / % + < <= > >= == != && || = Highest Lowest 5-15 . When OR is used in an expression.Short-Circuit Evaluation: Evaluation of a logical expression in left-toright order with evaluation stopping as soon as the final truth can be determined. the computer stops evaluation as soon as a FALSE condition is found.

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.Exercises 1 Given the following values for variables a. b and c are all less than 10 b) a > b >= c c) a does not equal either b or c d) a equals b but does not equal c 5-16 . Rewrite the following expressions so they would be valid in C++. a) a.

Max. Next check the weight requirements and store the result in a bool variable called weightOk. rejected for height only. Gender Male Female Min. Using these results. determine whether the candidate was accepted. Height 78 in. Height 62 in. Max. 60 in. 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. 5-17 . 185 lbs. Weight 130 lbs. 110 lbs. Weight 250 lbs. Output an appropriate message for each possible outcome.Boolean Expressions Programming Exercise A military academy accepts candidates according to the following height and weight requirements. Design a program that accepts as input the gender. 72 in. Min. rejected for weight only or rejected for both height and weight.

control branches to to the statement following the label. The general form for the switch statement is switch (IntegralExpression) { SwitchLabel…statement. The switch expression is evaluated and if the value matches one of the constants in the case label.Multi-way Selection The switch statement in C++ provides a way to eliminate some nested if structures. The SwitchLabel is either a case label or a default label. . From there it proceeds sequentially until the end of the switch statement or until a break is encountered. it looks for a default label and if found. } The general form for the SwitchLabel is case ConstantExpression: default: where • • • • The switch expression is the expression whose value determines which label is selected. If there is no matching label for the expression. Each case constant may appear only once in the statement. • 5-18 . control transfers to the statement following the end of the switch statement. . If no default label is present. In the case label. It cannot be a floating point expression. executes the statement following the label. the ConstantExpression must be an integral literal or a named constant.

case ‘R’ : cout << “You are a senior”. case ‘J’ : cout << “You are a junior”. break. default : cout << “You entered an invalid code”. break. // not necessary but a good habit } 5-19 . break. break. case ‘S’ : cout << “You are a sophomore”.Example: classCode ‘F’ Freshman ‘S’ Sophomore ‘J’ Junior ‘R’ Senior default Invalid switch (classCode) { case ‘F’ : cout << “You are a freshman”. break.

“average work” for C students. switch (classCode) { case ‘F’ : case ‘f’ : cout << “You are a freshman”. Suppose we wanted to allow for lower case input as well. etc. the program “follows through” can be helpful in some situations.The fact that without the break statement. 2 Write the C++ code to match the flowchart from #1. case ‘S’ : case ‘s’ : cout << “You are a sophomore”. Flowchart a code segment that reads a letter grade from the keyboard and prints “good work” for A and B students. and “poor work” for D and F students. 5-20 . 3 Draw the flowchart to convert the nested if into a switch statement. break. 4 Write the C++ code for the flowchart from #3. Draw this flowchart as a nested if. Switch Exercises: 1. break.

- 10158 (2)
- Lab02 Karnaugh Maps
- Itwa133 Midterm Practical Exam
- Chapter 8
- Chapter 6
- Learning-Area5 Programming
- FEU EAC ITES103 ITEI103 Flowcharting and Pseudocoding StudVersion
- ITES113_ITIE113-AY2011-2012
- 04-KarnaughMaps
- Teorya Ng Tulay Na Lupa
- Network Security Revised-Eric
- Lab Manual
- SECUNET Syll for PAASCU - Detailed-eric
- Chapter 8
- Chapter 7
- Chapter 6
- Chapter 9
- Chapter 5
- Chapter 3
- Chapter 2
- Chapter 1
- Datacomm Lab1 Osi Layer Model
- Datanet Final Exam 3t Sy0708
- Beekman7 Tb 10

Sign up to vote on this title

UsefulNot usefulsdsa

sdsa

- 03-Control_1pps.pdf
- Principles of Programming Java Level 1 - Jonathan Frank
- Ortega Notes (Comp)
- Clase Conexion
- Lecture03.Beamer 14099
- Conditional Stm Nts
- .cdsenv for Cadence Virtuoso
- Conditional Statements (Programming)
- ConditionsLoops 18
- c
- CM304
- etoolbox
- Analytical
- Malta Ariston Servisi | (0216) 414 3 830 | 7x24 Çağrı Merkezi
- 07 ES26 Lab - Multiway Selection
- Algorithms in Latex
- Operators
- Wrapper Class
- 4 Pages Checkin5
- PB8-PowerBuilder-SystemHierarchy
- Memo Java
- Lecture VB - Program Controls
- Wrapper.txt
- Primefaces Mobile Users Guide 0 9 4
- 12
- If Else Statement in C Program
- VB Script String Manipulation Functions
- ItemXSD to TablesMapping
- Istilah dalam Seiscomp3
- Java Tutorial Part 3
- Chapter 5