In C++, logical operations can be performed using boolean variables with the following logical operators:
-
Logical AND (
&&): Returnstrueif both operands are true.bool a = true; bool b = false; bool result = a && b; // result will be false -
Logical OR (
||): Returnstrueif at least one of the operands is true.bool a = true; bool b = false; bool result = a || b; // result will be true -
Logical NOT (
!): Returnstrueif the operand is false, and vice versa.bool a = true; bool result = !a; // result will be false
Example Code:
#include <iostream>
int main() {
bool isStudent = true;
bool hasPassedExam = false;
// Logical AND
bool canEnroll = isStudent && hasPassedExam;
std::cout << "Can Enroll: " << std::boolalpha << canEnroll << std::endl; // false
// Logical OR
bool hasScholarship = true;
bool canEnrollWithScholarship = isStudent || hasScholarship;
std::cout << "Can Enroll with Scholarship: " << canEnrollWithScholarship << std::endl; // true
// Logical NOT
bool isUnemployed = !hasPassedExam;
std::cout << "Is Unemployed: " << isUnemployed << std::endl; // true
return 0;
}
Output:
Can Enroll: false
Can Enroll with Scholarship: true
Is Unemployed: true
Summary:
Logical operations using boolean variables in C++ allow you to combine conditions and manipulate boolean values effectively. The logical operators &&, ||, and ! are essential for decision-making and control flow in your programs. If you have further questions or need clarification, feel free to ask!
