Unit 2 Cycle 1 Day 26: De Morgan's Applied to Code
Share
De Morgan's Applied to Code
Section Mixed — Review: Boolean Logic
Key Concept
Applying De Morgan's Laws to actual code requires recognizing the pattern and transforming it correctly. When negating !(age >= 18 && hasID), flip the AND to OR and negate each part: age < 18 || !hasID. The AP exam tests this with complex conditions involving method calls: !(str.length() > 0 || str.equals("none")) becomes str.length() <= 0 && !str.equals("none"). Practice transforming conditions in both directions — from the original to negated and from negated back to original.
Consider the following two code segments.
For which values of x and y do Segment 1 and Segment 2 produce different output?
Answer: (B) They always produce the same output.
By De Morgan's Law: !(x > 5 && y < 10) is equivalent to x <= 5 || y >= 10. The conditions are logically identical, so both segments always produce the same output (A or B, respectively).
Why Not the Others?
(A) They always produce the SAME output because the conditions are logically equivalent.
(C) With x=6, y=8: Seg1: !(true && true) = false, no print. Seg2: false || false = false, no print. Same.
(D) With x=3, y=12: Seg1: !(false && false) = true, print A. Seg2: true || true = true, print B. Both print.
Common Mistake
De Morgan's Law transforms !(a && b) into !a || !b. Negating x > 5 gives x <= 5 (flip operator AND include equality). Negating y < 10 gives y >= 10.
AP Exam Tip
When negating relational operators: > becomes <=, < becomes >=, == becomes !=. Always flip to the opposite that includes the boundary.