20 likes | 141 Views
5-4 Boolean Operators : Every Comparison yields a boolean (true or false) outcome. Machine Code (Binary) is based on whether or not a state is true(1) or false(0). Boolean Operators && “and” T && T -> T Both side must be true! || “or” T || F -> T At least one side must be true!
E N D
5-4 Boolean Operators : • Every Comparison yields a boolean (true or false) outcome. • Machine Code (Binary) is based on whether or not a state is true(1) or false(0). • Boolean Operators • && “and” T && T -> T Both side must be true! • || “or” T || F -> T At least one side must be true! • !“negate” !T -> F Negate or switch outcome • Examples: • if( x > 3 && x <= 10) // 3 < x < = 10 • if( x < 0 || x >= 5) • if( !(x >= 0)) // Same as? • if(!inRange(num)) // Write the most efficient inRange(x) for 3 < x < = 10 • DeMorgan’sLaw • !(A && B) = !A || !B • !(A || B) = !A && !B • Examples: • !( x > 0 && y <= 0) • !( x != 0 || y != 0) • !( x%2 != 0 || !( x%10 = = 0 && x % 5 = = 0)) • What do the following evaluate to? x = 3; y = x+4; if( x >= y/4 && x != y%2) y = 2x - y; else x = x-y; if( !(x<y) ) x = y -3x; else y=x;
Boolean Variables & Types: What are the differences between the following 3 inRange methods for 3 < x <= 10: 1. public booleaninRange(int num ) { if( num > 3 && num <= 10) // How many comparisons? return true; else return false; } 2. public booleaninRange(int num ) // How many comparisons? { return (num > 3 && num <= 10); } 3. public booleaninRange(int num ) // How many comparisons? { if(num > 3 ) if( num <= 10) return true; return false; // should we use an else? }