Conditionals & Boolean Expressions Lecture 3A Conditionals & Boolean Expressions Richard Gesick Figures from Lewis, “C# Software Solutions”, Addison Wesley
Topics Flow of Control Flow Diagram bool definition Relational Operators if statements else statements
Flow of Control Sequential Method calls Selection Looping Execute instructions in order Method calls Transfer control to method, execute instructions in method, then return with or without a value Selection Execute different instructions depending on data Looping Repeat a set of instructions for different data
A Flow Diagram Start End Ask for $$ Blame it on someone else Lay low and keep hidden Did you break anything? Yes Yes No Have your parents asked about it? Yes Are you lying? No Are you passing your classes? No No Yes Ask for $$ End
The Boolean A bool is a something that resolves to true or false You can get Boolean values several different ways Simple Complex These bools will be used (later) to make decisions
Relational Operators (for primitive data types) > greater than < less than == equals != not equal >= greater than or equal <= less than or equal Notice that all of these return us a true or false value
Relational Operator Examples Literal Example 5 > 3 // true 6 != 6 // false true == (4 <= 2) // false ‘c’ != ‘b’ // true !false // true Variable Example int num1 = 5; short num2 = 7; bool result = num2 > num1; //Note: result is now true
Logical Operators ! not && and || or
&& and || Operators These operators check for multiple conditions && (AND) needs both the left and the right to be true in order to return true || (OR) needs either one (or both) to be true to return true Examples: ( (6 > 5) && ( ‘c’ == ‘b’) ) // false ( (6 > 5) && ( 7 < 9) ) // true ( (6 > 5) || ( ‘c’ == ‘b’) ) // true ( (6 > 6) || ( ‘c’ == ‘b’) ) // false
Think + and * Think of the OR (||) operator as a +, with true = 1 and false = 0. Think of the AND (&&) operator as a *, with true =1 and false =0. True || False 1 + 0 = 1 (True) False && True 0 * 1 = 0 (False)
int x, y ; x = 4; y = 6; EXPRESSION VALUE x < y x + 2 < y x int x, y ; x = 4; y = 6; EXPRESSION VALUE x < y x + 2 < y x != y x + 3 >= y y == x y == x+2 true false
EXPRESSION VALUE 7 == 7 13 < 100 -17. 32. = -17. 32 -3. 0 == 0 true false
Suppose we have three ints x, y, and z, and we want to test if x is less than both y and z. A common error is to express the condition this incorrect way: x < y && z // compiler error Each operand of a logical operator must be a boolean expression. This is correct: x < y && x < z
Short-Circuit Evaluation For any logical operator, the operands are evaluated left to right If the result of the logical operation can be determined after evaluating the first operand, the second operand is not evaluated. If the first operand of an || is true, the result will be true If the first operand of an && is false, the result will be false
Operator Precedence Precedence Operator Associativity 1 () Innermost First 2 Unary operators: + - ++ -- ! (type) Right to left 3 * / % Left to right 4 + - 5 < <= > => 6 == != 7 && 8 || 9 = += -= *= /= %= Copyright © 2012 Pearson Education, Inc.
int age = 75; bool test; test = ( age > 18 && age < 65 ); C. O int age = 75; bool test; test = ( age > 18 && age < 65 ); C.O.Wln( age + " > 18 && " + age + " < 65 is " + test ); // short circuitry with AND test = ( age < 65 && age > 18 ); C.O.Wln( age + " < 65 && " + age + " > 18 is " + test ); // short circuitry with OR test = ( age > 65 || age < 18 ); C.O.Wln( age + " > 65 || " + age + " < 18 is " + test ); // AND has higher precedence than OR test = ( age > 65 || age < 18 && false ); C.O.Wln( age + " > 65 || " + age + " < 18 " + " && false is " + test ); // use of parentheses to force order of execution test = ( ( age > 65 || age < 18 ) && false ); C.O.Wln( "( " + age + " > 65 || " + age + " < 18 ) " + "&& false is " + test );
What is the value? float x = 3.0, y = 4.0, z = 2.0; EXPRESSION VALUE 1. (x > z) && (y > z) 2. (x + y / z) <= 3.5 3. (z > x) || (z > y) 4. !(y == z) 5. (x == 1.0) || (x == 3.0) 6. (z < x) && (x < y) 7. (x <= z) || (x >= y) 8. !(x > y) || y + z >= x – z 9. !((x > y) || ((y + z) >= (x – z))) true false
Now Let’s Do Something! Using the if statement, we can decide whether or not to execute some code Has format: if (<boolean value>) { // all the code that’s in here will only execute // if and only if the boolean above is true }
“if” Example { int start = 5; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start < end ) cout<< “A” <<endl; } cout<< “B” <<endl;
“if” Example A B { int start = 5; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start < end ) cout<< “A” <<endl; } cout<< “B” <<endl; Output A B
“if” Example { s int start = 5; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start > end ) cout<< “A” <<endl; } cout<< “B” <<endl; s
“if” Example B { int start = 5; using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start > end ) cout<< “A” <<endl; } cout<< “B” <<endl; Output B
The “else” statement if has a counterpart – the else statement If the if clause didn’t execute, the else clause will! Has format: if (<boolean value>) { // statements that execute if the boolean is true } else { // statements that execute if the boolean is false Notice only one set of statements executes, no matter what
“else” Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start > end ) cout<< “A” <<endl; } else cout<< “B” <<endl;
“else” Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start > end ) cout<< “A” <<endl; } else cout<< “B” <<endl; Output B
“else” Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start < end ) cout<< “A” <<endl; } else cout<< “B” <<endl;
“else” Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int end = 19; if (start < end ) cout<< “A” <<endl; } else cout<< “B” <<endl; Output A
else if’s Selecting one from many As soon as one is true, the rest are not considered Has format: if (<boolean value>) { // statements that execute if the above boolean is true } else if (<boolean value>){ else { // something that executes if nothing matched above
Combining into “else if”s (Selecting one from many) using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int middle = 8; int end = 19; if (start < middle ) { cout<< “A” ; } else if (start < end) { cout<< “B” ;
Combining into “else if”s (Selecting one from many) using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int middle = 8; int end = 19; if (start < middle ) { cout<< “A” ; } else if (start < end) { cout<< “B” ; Output A
else catch-all Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int middle = 8; int end = 19; if (start > middle ) { cout<< “A” ; } else if (start > end) { cout<< “B” ; else { cout<<"C";
else catch-all Example using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int start = 5; int middle = 8; int end = 19; if (start > middle ) { cout<< “A” ; } else if (start > end) { cout<< “B” ; else { cout<<"C"; Output C
Conclusion Boolean values can be generated several ways Use the if statement to decide which path to take Use the else to take the alternate path The else-if statements allow for selecting one from many
Indentation The statement controlled by the if statement is indented to indicate that relationship The use of a consistent indentation style makes a program easier to read and understand Although it makes no difference to the compiler, proper indentation is crucial "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding
Indentation 2 Remember that indentation is for the human reader, and is ignored by the computer if (total > MAX) cout<<"Error!!"; errorCount++; Despite what is implied by the indentation, the increment will occur whether the condition is true or not
Do not put a semicolon after the condition Do not put a semicolon after the condition. Doing so indicates that the true block is empty and can cause a logic error at run time.
What went wrong? This is only supposed to display “HEALTHY AIR” if the air quality index is between 50 and 80. But when you tested it, it displayed “HEALTHY AIR” when the index was 35. int AQIndex ; AQIndex = 35 ; if (50 < AQIndex < 80) cout<<“HEALTHY AIR“ ;
Analysis of Situation AQIndex = 35; According to the precedence chart, the expression (50 < AQIndex < 80) means (50 < AQIndex) < 80 because < is Left Associative (50 < AQIndex) is false (false < 80) is ???
Corrected Version AQIndex = 35 ; int AQIndex ; AQIndex = 35 ; if ( (50 < AQIndex) && (AQIndex < 80) ) cout<<“HEALTHY AIR“ ;
What happens if you omit braces? if ( (carDoors == 4 ) && (driverAge > 24) ) premium = 650.00 ; cout<<“ LOW RISK “; else premium = 1200.00 ; cout<<“ HIGH RISK ”; monthlyPayment = premium / 12.0 + 5.00; COMPILER ERROR OCCURS. The “if clause” is the single statement following the if.
Braces can only be omitted when each clause is a single statement if ( lastInitial <= ‘K’ ) volume = 1; else volume = 2; cout<<“Look it up in volume # “ << volume << “ of NYC phone book”;
If-Then-Else for a mail order Assign value .25 to discountRate and assign value 10.00 to shipCost if purchase is over 100.00 Otherwise, assign value .15 to discountRate and assign value 5.00 to shipCost Either way, calculate totalBill
These braces cannot be omitted if ( purchase > 100.00 ) { discountRate = .25 ; shipCost = 10.00 ; } else discountRate = .15 ; shipCost = 5.00 ; totalBill = purchase * (1.0 - discountRate) + shipCost ;