C++ Logical Operator

In this tutorial we will study C++ logical operator in detail. C++ logical operators are used mostly inside the condition statement such as if,if…else where we want multiple conditions.

C++ Logical Operator

  1. Logical Operators are used if we want to compare more than one condition.
  2. Depending upon the requirement, proper logical operator is used.
  3. Following table shows us the different C++ operators available.
Operators Name of the Operator Type
&& AND Operator Binary
|| OR Operator Binary
! NOT Operator Unary

According to names of the Logical Operators, the condition satisfied in following situation and expected outputs are given

Operator Output
AND Output is 1 only when conditions on both sides of Operator become True
OR Output is 0 only when conditions on both sides of Operator become False
NOT It gives inverted Output

Let us look at all logical operators with example-

C++ Program : Logical Operator

#include<iostream>
using namespace std;
int main()
{
   int num1=30;
   int num2=40;
   if(num1>=40 || num2>=40)
      cout<<"OR If Block Gets Executed"<<endl;
   if(num1>=20 && num2>=20)
      cout<<"AND If Block Gets Executed"<<endl;
   if(!(num1>=40))
      cout<<"NOT If Block Gets Executed"<<endl;
   return 0;
}

Output:

OR If Block Gets Executed
AND If Block Gets Executed
NOT If Block Gets Executed

Explanation of the Program

Or statement gives output = 1 when any of the two condition is satisfied.

if(num1>40 || num2>=40)

Here in above program , num2=40. So one of the two conditions is satisfied. So statement is executed.

For AND operator, output is 1 only when both conditions are satisfied.

if(num1>=20 && num2>=20)

Thus in above program, both the conditions are True so if block gets executed.

Truth table

Operator 1st Condition 2nd Condition Output
AND True True True
True False False
False True False
False False False
OR True True True
True False True
False True True
False False False
NOT True - False
False - True