# C++ Logical Operators for beginner to expert

Logical operators are used to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0.

In C++, logical operators are commonly used in decision making. To further understand the logical operators, let’s see the following examples,

```Suppose,
a = 5
b = 8

Then,

(a > 3) && (b > 5) evaluates to true
(a > 3)  && (b < 5) evaluates to false

(a > 3) || (b > 5) evaluates to true
(a > 3) || (b < 5) evaluates to true
(a < 3) || (b < 5) evaluates to false

!(a < 3) evaluates to true
!(a > 3) evaluates to false```

### Example: Logical Operators

```#include <iostream>
using namespace std;

int main() {
bool result;

result = (3 != 5) && (3 < 5);     // true
cout << "(3 != 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 < 5);    // false
cout << "(3 == 5) && (3 < 5) is " << result << endl;

result = (3 == 5) && (3 > 5);    // false
cout << "(3 == 5) && (3 > 5) is " << result << endl;

result = (3 != 5) || (3 < 5);    // true
cout << "(3 != 5) || (3 < 5) is " << result << endl;

result = (3 != 5) || (3 > 5);    // true
cout << "(3 != 5) || (3 > 5) is " << result << endl;

result = (3 == 5) || (3 > 5);    // false
cout << "(3 == 5) || (3 > 5) is " << result << endl;

result = !(5 == 2);    // true
cout << "!(5 == 2) is " << result << endl;

result = !(5 == 5);    // false
cout << "!(5 == 5) is " << result << endl;

return 0;
};```

Output

```(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0```

Explanation of logical operator program

• `(3 != 5) && (3 < 5)` evaluates to 1 because both operands `(3 != 5)` and `(3 < 5)` are 1 (true).
• `(3 == 5) && (3 < 5)` evaluates to 0 because the operand `(3 == 5)` is 0 (false).
• `(3 == 5) && (3 > 5)` evaluates to 0 because both operands `(3 == 5)` and `(3 > 5)` are 0 (false).
• `(3 != 5) || (3 < 5)` evaluates to 1 because both operands `(3 != 5)` and `(3 < 5)` are 1 (true).
• `(3 != 5) || (3 > 5)` evaluates to 1 because the operand `(3 != 5)` is 1 (true).
• `(3 == 5) || (3 > 5)` evaluates to 0 because both operands `(3 == 5)` and `(3 > 5)` are 0 (false).
• `!(5 == 2)` evaluates to 1 because the operand `(5 == 2)` is 0 (false).
• `!(5 == 5)` evaluates to 0 because the operand `(5 == 5)` is 1 (true). 5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

## One thought on “C++ Logical Operators for beginner to expert”

1. […] Logical Operators […]