Sometimes we need to combine logical operators to evaluate more complex conditions. For example:
7 >= 10 && (5 == 7 || 9 < 12) // Evaluates to false
Notice that we used parentheses to group 5 == 7 and 9 < 12 together. The computer interprets this line of code as condition1 && condition2 where:
condition1is 7 >= 10, which is falsecondition2is (5 == 7 || 9 < 12), which is true
condition1 and condition2 is false, so the entire condition is false.
It is very important to use parentheses to tell the computer how to group the conditions together. If we change the parentheses in the example above to:
(7 >= 10 && 5 == 7) || 9 < 12 // Evaluates to true
Now the computer interprets this line of code as condition1 || condition2 where:
condition1is (7 >= 10 && 5 == 7), which is falsecondition2is 9 < 12, which is true
condition1 and condition2 is true, so the entire condition is true.
Assignment
Follow the Coding Tutorial and let's combine some logical operators.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.