C++ Logical Operators



Logical operators perform logical operations on Boolean values or expressions. These operators are used to combine two or more conditions and help in decision-making.

Types of Logical Operators

C++ provides three logical operators:

  • Logical AND (&&)
  • Logical OR (||)
  • Logical NOT (!)

1. Logical AND (&&)

The logical AND operator returns true only if both operands are true. If any operand is false, the result is false.

The syntax of logical AND is:

condition_1 && condition 2

2. Logical OR (||)

The logical OR operator returns true if at least one of the conditions is true. If both are false, it returns false.

The syntax of logical OR is:

condition_1 || condition 2

3. Logical NOT (!)

The logical NOT operator negates the given condition. If a condition is true, it returns false and vice versa.

The syntax of logical NOT is:

!condition

Example of Logical Operators

Try the following example to understand all the logical operators available in C++.

Copy and paste the following C++ program in test.cpp file and compile and run this program.

#include <iostream>
using namespace std;

main() {
   int a = 5;
   int b = 20;
   int c ;

   if(a && b) {
      cout << "Line 1 - Condition is true"<< endl ;
   }
   
   if(a || b) {
      cout << "Line 2 - Condition is true"<< endl ;
   }
   
   /* Let's change the values of  a and b */
   a = 0;
   b = 10;
   
   if(a && b) {
      cout << "Line 3 - Condition is true"<< endl ;
   } else {
      cout << "Line 4 - Condition is not true"<< endl ;
   }
   
   if(!(a && b)) {
      cout << "Line 5 - Condition is true"<< endl ;
   }
   
   return 0;
}

When the above code is compiled and executed, it produces the following result −

Line 1 - Condition is true
Line 2 - Condition is true
Line 4 - Condition is not true
Line 5 - Condition is true
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy