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>usingnamespace 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 ;}return0;}

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *