Logical Operators in C ++
Logical Operators in C++
Logical operators in C++ are used to combine multiple conditions or expressions into a single logical expression. They are essential for making decisions and controlling the flow of execution in your programs.
Types of Logical Operators:
* Logical AND (&&)
* Returns true only if both operands are true.
* Example: (a > 0) && (b < 10)
* Logical OR (||)
* Returns true if at least one of the operands is true.
* Example: (a == 5) || (b == 10)
* Logical NOT (!)
* Reverses the logical state of its operand.
* Example: !(a > 0)
Truth Table:
| Operator | Operand 1 | Operand 2 | Result |
|---|---|---|---|
| && | true | true | true |
| && | true | false | false |
| && | false | true | false |
| && | false | false | false |
| ` | | ` | true |
| ` | | ` | true |
| ` | | ` | false |
| ` | | ` | false |
| ! | true | | false |
| ! | false | | true |
Example:
#include <iostream>
int main() {
int a = 5, b = 10;
if ((a > 0) && (b < 20)) {
std::cout << "Both conditions are true." << std::endl;
}
if ((a == 3) || (b == 10)) {
std::cout << "At least one condition is true." << std::endl;
}
if (!(a < 0)) {
std::cout << "a is not less than 0." << std::endl;
}
return 0;
}
Output:
Both conditions are true.
At least one condition is true.
a is not less than 0.
Key Points:
* Logical operators are used to combine conditions in if, else if, while, for, and other control flow statements.
* The && operator has higher precedence than the || operator.
* Parentheses can be used to control the order of evaluation.
* Logical operators are essential for writing complex decision-making logic in your C++ programs.
Comments
Post a Comment