gameOver = score1>=10 || score2>=10; This would not work though in the event that both scores were the same (the game would be tied). So the program would also need to check whether or not the two scores were the same. Let's revise: gameOver = score1>=10 || score2>=10 && score1!=score2; This new form checks to see whether either score is at least 10 and that the two scores are different (so one player has more points than the other, ending the game). Only one problem - it will not work due to the order of operations for logical operators. The order of operations for logical operators is NOT, AND, OR (!, &&, ||). So ! is evaluated first, then &&, followed by ||. So to make the above expression work as intended, parentheses must be added around the OR part so that is evaluated first (otherwise, it evaluates the AND first, potentially causing an invalid result). gameOver = (score1>=10 || score2>=10) && score1!=score2; Truth Tables Up to this point, you have informally learned the following about AND and OR: 1. AND (&&) is only true when both of its operands are true
Evaluating Compound Boolean Expressions In the following expression, assume that A, B and C are declared as boolean variables and that A=false, B=false and C=false. To evaluate the expression we will use the truth tables and the order of operations discussed in this lesson.
Substituting the values of the variables we get:
We begin with the parentheses which evaluate to false since both B and C are false. We now have an expression that reads
Evaluating the !'s reduces it to
Now evaluate the AND
Finally, evaluate the OR to get
DeMorgan's Laws British Mathematician Augustus DeMorgan first discovered the following two theorems which now bear his name:
To help you remember them, notice that the ! acts like a negative sign in front of parentheses in Algebra, changing everything inside to its opposite. DeMorgan's Laws become useful in eliminating parentheses in some compound Boolean expressions. Here is an example:
would become
|
|||||||||||||||||||||||||||||||
© DanShuster.com