De Morgan's Laws & Negating Conditions
Part of: Boolean Expressions & if Statements
Negating Compound Conditions. Sometimes you need the opposite of a compound boolean. De Morgan's Laws tell you exactly how to distribute a ! across && and . They are two algebraic identities: - !(a && b) is equivalent to !a !b - !(a b) is equivalent to !a && !b The pattern: negate each operand and flip the operator (&& becomes , and becomes &&). Why This Matters. Consider a rule: "reject if NOT (age = 18 AND citizen)". Applying De Morgan's Law: Notice !(age = 18) becomes age < 18 because the negation of = is <. Negating relational operators is part of the skill: - !(a < b) is a = b - !(a b) is a <= b - !(a == b) is a != b - !(a != b) is a == b A Full Example. You could rewrite !open using De Morgan's Laws into a positive form, but the law guarantees the two versions behave identically for every input. What usually goes wrong. What you see What caused it How to fix it --- --- --- Every input prints IN The rewritten condition kept &&, and no number is both below 10 and above 20, so it can never be true Negating an AND turns it into an OR 15 prints OUT Only one of the two comparisons was negated Both comparisons flip when the NOT is distributed 10 and 20 print OUT The bounds were nega
Challenge: Outside the Range