Main content
AP®︎/College Computer Science Principles
Course: AP®︎/College Computer Science Principles > Unit 3
Lesson 6: Logical equivalenceEquivalence between conditionals and Booleans
It's important to understand logical equivalence when writing computer programs so that your program's behavior is both logically correct and understandable by other programmers. There are many ways to write code that is logically equivalent, but there is often one way that is clearer and more concise than the others.
Let's look at some logical flows in pseudocode that can be simplified using logical equivalence rules and alternative programming structures.
Structural equivalence
First, let’s consider an example where we are trying to set a variable which reports if something is frequently used. We might write code like:
if (numUsers > 100) {
isFrequentlyUsed ← true
} else {
isFrequentlyUsed ← false
}
This seems like perfectly reasonable and clear code. However, the astute observer will note that the only operation done in each block of the if/else is setting the value of
isFrequentlyUsed
. It sets that value to:true
ifnumUsers > 100
istrue
false
in the else case (wherenumUsers > 100
isfalse
)
We can replace the entire if/else block with a single line of code:
isFrequentlyUsed ← numUsers > 100
This will check
numUsers > 100
, produce a boolean (true
or false
), and then assign the value directly to the variable isFrequentlyUsed
To generalize this rule, if there's an if/else of this form:
if (E) {
V ← true
} else {
V ← false
}
This statement is logically equivalent:
V ← E
Structural equivalence with negation
Consider the code below that does a similar but opposite operation, reporting if something is rarely used:
if (numUsers > 100) {
isRarelyUsed ← false
} else {
isRarelyUsed ← true
}
At first, it seems like we are stuck because now our code is doing the opposite of the above. It sets the value to:
false
ifnumUsers > 100
istrue
(not the same value!)true
otherwise (whennumUsers > 100
isfalse
)
Fortunately, we can use the logical equivalence rule from the first article on equivalent simple booleans, and use
NOT
to get the opposite value of a Boolean.So the above if/else is the same as this line of code:
isRarelyUsed ← NOT (numUsers > 100)
In general our rule is this:
if (E) {
V ← false
} else {
V ← true
}
Can be replaced by:
V ← NOT (E)
Want to join the conversation?
- Congratulations if you made it this far, keep going!(13 votes)
- So you use a boolean(I love knowing what it is it brings me power, just like knowing the Mitochondria is the powerhouse of the cell), to identify the line of code above?
The Mitochondria is the powerhouse of the cell.(4 votes)