Boolean Tricks
Expressions in Conditions Condition must evaluate to Boolean but can be arbitrarily complex
Expressions in Conditions Condition must evaluate to Boolean but can be arbitrarily complex Just because you can doesn't mean you should. Better:
% Check if x is a multiple of y: x % y == 0
Even/Odd x % 2 is: – 0 even – 1 odd
Comparing Floating Points According to C++: 3.02 != ( ) Do NOT compare floats directly with == or !=
Comparing Floating Points Compare if two floating points are "close enough" |num1 – num2| < threshold
Comparing Floating Points Compare if two floating points are "close enough" |num1 – num2| < threshold absolute value: abs(expression) – in threshold – depends on problem, have 15 significant digits to work with
Comparing Floating Points
Naked Booleans Boolean variable can be used as condition: Same as:
! ! is "not" Preferred to:
Problem Want to read in temperature and print "Temp is good" if it is between 68 and 72, or warning if it is too hot/cold.
Boolean Flags Flag variable : Boolean used to track condition – Start as true or false – Modify based on eveidence
Nested Ifs
Nested ifs Conditionals can be "nested"
If/Else Matching This code has a logic error:
If/Else Matching This code has a logic error:
If/Else Matching What computer saw:
If/Else Matching { } make ending of if/else explicit Editor will show brace matching Use indentation as visual clue
If/Else If can be the body of an else:
If/Else if… else if… else if… else form: – More compact/legible – Only one option is chosen
Bad If/Else A chain of plain if's not mutually exclusive!
Example: Computing Taxes The US federal personal income tax is calculated based on the filing status and taxable income. There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. Read in someone's status and income and determine their tax:
Conditions 2 Inputs – Marital status – $ earned 1 Output: tax
What happens? No matter what: – Get status – Get income – Print tax Conditionally: – What math to do
Step 1 Distinguish based on status
Step 2 Refine each category based on earnings: