(^162) | Selection and Encapsulation
(^2) In Boolean algebra, the pattern is formalized by a theorem called DeMorgan’s law.
false, then !(grade == 'A')is true. NOT gives us a convenient way of reversing the meaning
of an assertion. For example,
!(hours > 40)
is the equivalent of
hours <= 40
In some contexts, the first form is clearer; in others, the second makes more sense.
The following pairs of expressions are equivalent:
Expression Equivalent Expression
!(a == b) a != b
!(a == b || a == c) a != b && a != c
!(a == b && c > d) a != b || c <= d
Take a close look at these expressions to be sure you understand why they are equiva-
lent. Try evaluating them with some values for a,b,c, and d. Notice the pattern: The expres-
sion on the left is just the one to its right with !added and the relational and logical operators
reversed (for example,==instead of !=and ||instead of &&). Remember this pattern. It allows
you to rewrite expressions in the simplest form.^2
You can apply logical operators to the results of comparisons. You can also apply them
directly to variables of type boolean. For example, instead of writing
isElector = (age >= 18 && district == 23);
to assign a value to the booleanvariable isElector, we could use two intermediate booleanvari-
ables,isVoterand isConstituent:
isVoter = (age >= 18);
isConstituent = (district == 23);
isElector = isVoter && isConstituent;
The following tables summarize the results of applying &&and ||to a pair of logical ex-
pressions (represented here by the booleanvariables xand y).
Value of x Value of y Value of (x && y)
true true true
true false false
false true false
false false false
やまだぃちぅ
(やまだぃちぅ)
#1