Thursday, April 25, 2024 02:30

Table of contents >> Introduction > Logical operators

Logical operators

Logical operators are quite simple, since they can only produce two outputs: true or false. The basic logical (Boolean) operators are AND (&&), OR (||),  XOR (also called “Exclusive OR”, ^) and NOT (or negation, !).

I will show you a sample of the four logical operations and the results that they produce:

From the above example, we can summarize the following aspects: AND will return a true value only when BOTH operands are true. On the other side, OR will return true if at least ONE of the operands is true. Complementary to this behavior, XOR will return true only when a SINGLE operand is true. We can also notice that NOT will simply invert the initial value, the result being false when the operand is true, and true when the initial value is false.

In the case of OR operation, if both operands are true, the result will be true; if they are both false, the result will be false.

The concepts explained in this lesson are also shown visually as part of the following video:

 

EXERCISES
1. Write a Boolean expression that checks whether a given integer is divisible by both 5 and 7, without a remainder.

Solution


Guidelines: Use a logical AND (&& operator) and the remainder operation % in division. You can also solve the problem by only one test: the division of 35 (think why).

Tags: ,

Leave a Reply



Follow the white rabbit