In this tutorial, you will learn about different Logical Operators available in C++ programming language and go through each of these Logical Operators with examples.
C++ Logical Operators
Logical Operators are used to perform boolean operations like AND, OR, and NOT.
Operators
The following table specifies symbol, example, and description for each of the Logical Operator in C++.
Operator Symbol | Logical Operation | Example | Description |
&& | AND | a && b | Returns boolean AND of a and b. |
|| | OR | a && b | Returns boolean OR of a and b. |
! | NOT | !a | Returns Negation or boolean NOT of a. |
1. Logical AND (&&)
The following is the truth table for AND operation.
Operand 1 | Operand 2 | Returns |
true | true | true |
true | false | false |
false | true | false |
false | false | false |
main.cpp
</>
Copy
#include <iostream>
using namespace std;
int main() {
int a = 10;
if ((a < 100) && (a%2 == 0)) {
cout << "a is even and less than 100." << endl;
}
}
Output
a is even and less than 100.
2. Logical OR (||)
The following is truth table for OR operation.
Operand 1 | Operand 2 | Returns |
true | true | true |
true | false | true |
false | true | true |
false | false | false |
main.cpp
</>
Copy
#include <iostream>
using namespace std;
int main() {
int a = 7;
if ((a < 10) || (a%2 == 0)) {
cout << "a is even or less than 10." << endl;
}
}
Output
a is even or less than 10.
3. Logical NOT (!)
The following is truth table for NOT operation.
Operand | Returns |
true | false |
false | true |
main.cpp
</>
Copy
#include <iostream>
using namespace std;
int main() {
int a = 7;
if (!(a%2 == 0)) {
cout << "a is not even." << endl;
}
}
Output
a is not even.
Conclusion
In this C++ Tutorial, we have learned what Logical operators are, which logical operators are available in C++, and how to use them, with the help of examples programs.