1
Class #12: Selection, Logic, and Control, II
Software Design I (CS 120): D. Mathias
Evaluating boolean Expressions
} The simple numeric comparison
- perators and equality relations
are easy to evaluate
} T
- determine whether a more
complex logical formula is true or false, we use truth tables for logical operators
Software Design I (CS 120) 2
P ! P T F F T
P Q P || Q T T T T F T F T T F F F P Q P && Q T T T T F F F T F F F F
Writing boolean Expressions
} The logical operators allow us to write more complex if-
conditions, to check more complex properties
} E.g., we can check if integer x is between 1 and 10 (inclusive): } Sometimes this is just for convenience: for example, both of the
following pieces of code do the same thing:
Software Design I (CS 120) 3
if ( ( x >= 1 ) && ( x <= 10 ) ) { System.out.println( x + “ is between 1 and 10” ); } if ( x <= 0 ) { System.out.println( x + “ is <= than 0” ); } if ( !( x > 0 ) ) { System.out.println( x + “ is <= than 0” ); }
Evaluating boolean Expressions
} Using the basic truth tables, and our precedence rules, we
can evaluate any complex logical expression we like…
Software Design I (CS 120) 4
P Q ! P && Q T T T F F T F F F F T T F F T F
Step 1: evaluate the highest-priority
- perator (! == NOT)
Step 2: evaluate the lower-priority operator (&& == AND)