Logical Operators in C++ | Different Logical Operators
Logical operators are used to evaluate compound conditions. A logical operator is a binary operation that returns either true or false. Logical operators are commonly used in programming languages to perform boolean operations. In C++,
The following are some examples of logical operators: && (and), || (or), !(Not)
Operators | Name | Example | Description |
&& | AND | x < 6 && x < 12 | Returns true if both statements are true |
|| | OR | x < 6 || x < 12 | Returns true if one of the statements is true |
! | NOT | !(x < 6 && x < 12) | Reverse the result, returns false if the result is true |
Different logical Operators in C++
There are three logical operators in C++
AND Operator (&&)
The symbol used for an operator is (&&). It is used to evaluate two conditions. It produces a true result if both conditions are true. It produces a false result if any one condition is false.
Condition 1 | Operator | Condition 2 | Result |
False | && | False | False |
False | && | True | False |
True | && | False | False |
True | && | True | True |
Example
#include <iostream>
using namespace std;
int main()
{
int x = 6;
int y = 4;
cout << (x > 5 && y < 12); // returns true (1) because 6 is greater than 5 AND 6 is less than 12
return 0;
}
OR Operator (||)
The symbol used for the OR operator is (||). It is used to evaluate two conditions. It gives a true result if either condition is true. It gives false results if both conditions are false.
Condition 1 | Operator | Condition 2 | Result |
False | || | False | False |
False | || | True | True |
True | || | False | True |
True | || | True | True |
Example
#include <iostream>
using namespace std;
int main() {
int x = 6;
int y = 4;
cout << (x > 5 || y < 3); // returns true (1) because one of the conditions are true (6 is greater than 5, but 4 is not less than 3)
return 0;
}
NOT Operator (!)
The symbol used for NOT operator is (!). it is used to reverse the result of a condition. It gives true result if the condition is false. It gives false result if the condition is true.
Operator | Condition | Result |
! | True | False |
! | False | True |
Example
#include <iostream>
using namespace std;
int main() {
int x = 6;
int y = 4;
cout << (!(x > 5 || y < 3); // returns False (0), because the condition is true.
return 0;
}
Leave a Reply