Logical operators in C++ are used to combine or reverse conditions. They are mainly used in decision-making statements like if, while, and loops.
What are Logical Operators?
Logical operators work with boolean expressions and return:
true(1)false(0)
They help combine multiple conditions in a program.
Types of Logical Operators in C++
| Operator | Meaning |
|---|---|
&& | Logical AND |
| ` | |
! | Logical NOT |
Logical AND Operator (&&)
The AND operator returns true only if both conditions are true.
Example
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 5;
cout << (a > 5 && b < 10);
return 0;
}
Output
1
Logical OR Operator (||)
The OR operator returns true if at least one condition is true.
Example
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
cout << (a > 5 || b < 10);
return 0;
}
Output
1
Logical NOT Operator (!)
The NOT operator reverses the result:
truebecomesfalsefalsebecomestrue
Example
#include <iostream>
using namespace std;
int main() {
bool value = true;
cout << !value;
return 0;
}
Output
0
Complete Example Program
#include <iostream>
using namespace std;
int main() {
int age = 20;
int marks = 80;
cout << (age >= 18 && marks >= 50) << endl;
cout << (age < 18 || marks >= 50) << endl;
cout << !(age >= 18) << endl;
return 0;
}
Output
1
1
0
Truth Table of Logical Operators
| A | B | A && B | A || B |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 |
| 1 | 0 | 0 | 1 |
| 1 | 1 | 1 | 1 |
Using Logical Operators in Conditions
Example
if (username == "admin" && password == "1234") {
cout << "Login Successful";
}
Important Points
- Logical operators work with conditions
- They return boolean results
- Used in decision-making and loops
&&needs all conditions true||needs at least one condition true
Why Logical Operators are Important
They are important because they:
- Combine multiple conditions
- Control program flow
- Help in complex decision-making
- Improve programming logic
Real-Life Example
Logical operators are used in:
- Login systems
- Exam eligibility checking
- Game conditions
- Security systems
- Banking applications
Conclusion
Logical operators in C++ are essential for combining and controlling conditions in programs. They help create smart and interactive applications by allowing programs to make logical decisions efficiently.