Course Content
C++ Introduction
C++ Introduction
2. Introduction to Operators
4. Introduction to Program Flow
5. Introduction to Functions
Logical Operators
You can use logical operators AND (&&
), OR (||
) and NOT (!
) to evaluate multiple conditions simultaneously.
-
AND (
&&
) returnstrue
only if both conditions are true. For example, checking if an account balance is sufficient and the withdrawal amount is positive; -
OR (
||
) returnstrue
if at least one condition is true. For example, checking if a balance is sufficient or the user has a credit card; -
NOT (
!
) negates a condition, turningtrue
intofalse
and vice versa. For example, checking if an account is not locked.
Imagine you need to create conditions for user authentication. Let’s explore some scenarios.
Condition | Authorization Status | State of Password, Login, Phone Call, and Internet |
---|---|---|
Password AND login are correct | Authorized (true ) | Password: true Login: true Phone Call: N/A Internet: N/A |
Password AND login are correct, OR with a phone call identification | Authorized (true ) | Password: true Login: false Phone Call: true Internet: N/A |
There is NO internet | Not Authorized (false ) | Password: N/A Login: N/A Phone Call: N/A Internet: false |
logical_and
logical_or
logical_not
#include <iostream> int main() { // Using AND (&&) operator for password and login // Login is correct = `true` // Password is correct = `true` std::cout << "User authorized (password AND login correct)" << (true && true) << std::endl; }
1. Which logical operator is used to check if both conditions are true?
2. Which logical operator is used to check if at least one condition is true?
3. What does the !
operator do?
Everything was clear?
Thanks for your feedback!
Section 2. Chapter 4