C++ Logical Operators
Logical operators in C++ are used to combine multiple relational or boolean expressions. They return a boolean result: true (1) or false (0). This tutorial provides separate examples for each operator and a combined program demonstrating logical operations.
1. Logical AND (&&)
The logical AND operator returns true if **both operands are true**. Otherwise, it returns false.
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10;
if(a > 0 && b > 0)
cout << "Both a and b are positive" << endl;
else
cout << "At least one is not positive" << endl;
return 0;
}
2. Logical OR (||)
The logical OR operator returns true if **at least one operand is true**. It returns false only if both operands are false.
#include <iostream>
using namespace std;
int main() {
int a = -5, b = 10;
if(a > 0 || b > 0)
cout << "At least one number is positive" << endl;
else
cout << "Neither number is positive" << endl;
return 0;
}
3. Logical NOT (!)
The logical NOT operator negates a boolean expression. It returns true if the expression is false, and false if the expression is true.
#include <iostream>
using namespace std;
int main() {
bool isTrue = false;
if(!isTrue)
cout << "The expression is false" << endl;
else
cout << "The expression is true" << endl;
return 0;
}
4. Combined Program
This program demonstrates all logical operators together with relational expressions.
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10;
cout << "(a > 0 && b > 0): " << (a > 0 && b > 0) << endl;
cout << "(a < 0 || b > 0): " << (a < 0 || b > 0) << endl;
cout << "!(a > b): " << (!(a > b)) << endl;
return 0;
}
Conclusion
Logical operators in C++ allow combining multiple conditions. Separate examples and a combined program make it easier to understand the behavior of &&, ||, and ! operators.
Codecrown