Introduction and Overview

Hello, budding programmer! Let's dive into the topic of Logical Operators in C++. These special symbols, &&, ||, and !, guide our program's decision-making process. In this lesson, we aim to demystify these operators and explain how they function in control structures such as if and switch statements.

Logical Operators in C++

Jumping right in, we've identified three logical operators:

  1. Logical AND (&&): This yields true if both conditions are true.
  2. Logical OR (||): This yields true if any one condition is true.
  3. Logical NOT (!): This operator reverses the truth value of a condition.

These operators work in conjunction with Boolean values (true and false) in a program. Here are some examples:

#include <iostream> 

int main() {
   bool isDay = true; // Variable indicating it is day
   bool isNight = false; // Variable indicating it is not night

   // Using Logical AND
   std::cout << "Is it day AND night? " << (isDay && isNight); // Outputs 0 (false)

   // Using Logical OR
   std::cout << "Is it day OR night? " << (isDay || isNight); // Outputs 1 (true)

   // Using Logical NOT
   std::cout << "Is it NOT day? " << (!isDay); // Outputs 0 (false)

   return 0;
}
Understanding Truth Tables

To depict all possible logical operator outcomes, we turn to Truth Tables. Let's review each of them:

AND (&&):

ABA && B
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

OR (||):

ABA || B
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

NOT (!):

A!A
truefalse
falsetrue

These tables neatly illustrate the outcomes of the logical operators based on all possible combinations of Boolean values.

Application of Logical Operators in Control Structures

Now, let's put theory into practice by learning how to use logical operators within control structures.

Consider a scenario in which a student can go on a field trip only if it's a weekday and they have their parents' permission. In this case, the if condition checks both isWeekday and hasPermission using the Logical AND operator.

#include <iostream> 

int main() {
   bool isWeekday = true; // Variable indicating it's a weekday
   bool hasPermission = true; // Variable indicating student has parents' permission

   if (isWeekday && hasPermission) { // If both conditions are true
       std::cout << "The student can go to the field trip.";
   }
   else {
       std::cout << "The student can't go to the field trip.";
   }

   return 0;
} // Outputs 'The student can go to the field trip.'
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal