20 likes | 157 Views
This guide explores the fundamental concepts of Boolean operators, which yield true or false outcomes based on conditions. It covers machine code's reliance on binary states (true as 1 and false as 0) and demonstrates the use of operators like "&&" (and), "||" (or), and "!" (negate). Through examples, including comparisons and DeMorgan’s Laws, we illustrate the practical applications of these operators in functions such as evaluating conditions in programming. Learn how to efficiently implement Boolean logic in your code to process multiple conditions effectively.
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? }