Boolean Operators
Booleans Operators
You can also connect boolean expressions together using the &&
(AND) and the ||
(OR) operator. For example, suppose I ask: “Are you a human, and is Nuvi a robot?” The word “and” connects the two true-false questions together. In this case, since it is true that you are a human, and it is also true that Nuvi is a robot, then the overall result is true
.
Here’s a chart that describes what happens when we connect booleans together:
Expression | Result | Expression | Result |
---|---|---|---|
true && true | true | true || true | true |
true && false | false | true || false | true |
false && true | false | false || true | true |
false && false | false | false || false | false |
To summarize, &&
requires both Boolean expressions to be true, while ||
only requires one of the two Boolean expressions to be true
. Here are some more examples:
(5 < 8) && (9 != 10)
producestrue
since both5
is less than8
and9
is not equal to10
.(8 <= 2) || ("h" + "e" == "he")
producestrue
since"h" + "e"
results in"he"
, even though8
is not less than or equal to2
.(6 != 2 * 3) || (8 < 2 * 4)
producesfalse
since both6
not equal to2 * 3
, and8
not being less than2 * 4
, producefalse
.
Working Together
Try guessing the answers to the following expressions. Use Console.WriteLine
to print out the answers.
(9 < 10) && (12 => 11)
(15 - 2 == 11) || (4 % 3 != 2)