3 Types of logical operators in C++

3 Types of logical operators in C++



Logical operators combine relational expressions. The output of a logical expression is always 1 or 0.

There are 3 Types of logical operators in C++ as follows:

i. Logical AND operator in C++ (&&)

&&(Double Ampersand)  is known as  Logical AND  operator in C++.  If any input to logical AND operator is 0, output is  0. If all the inputs of logical AND  are 1, output is  1.

Truth table for Logical AND operator is

Input1 Input2 Output
0 0 0
0 1 0
1 0 0
1 1 1

Examples

4>3 && 7>5  =1  //Result is 1 as 4>3 is 1  and 7>5  is also 1.

4 >3 && 7<5 = 0 //Result is 0 as 4>3 is 1  and 7<5  is 0.

ii. Logical OR operator in C++ (||)

|| (Double Pipes) is called  Logical OR operator. If any input of logical OR operator is 1, output is 1. If all inputs are 0, output is 0.

Truth table for Logical OR operator is

Input1 Input2 Output
0 0 0
0 1 1
1 0 1
1 1 1

Examples

7>3 || 7<5 = 1  //Result is 1 as 7>3 is 1  and 7<5  is  0.

7<3 || 7<5  =0 //Result is 0 as 7<3 is 0 and 7<5  is  also 0.

iii. Logical NOT operator in C++ (!)

! (Sign of Exclamation) is called Logical NOT operator. If input of logical NOT operator is 1, output is 0. If input is 0, output is 1.

Truth table for Logical Not operator is

Input Output
0 1
1 0

Examples

!(7 >3) = 0  //Result is 0 as 7>3 is 1  and reverse of 1 is 0.

!(7<5) = 1  //Result is 1 as 7<5 is 0  and reverse of  0 is 1.

 //Program to demonstrate the use of logical operators.

#include<iostream> 
using namespace std;
int main()
{
  int a=10,b=3;
  cout<<”\na>0 && b>0=”<<(a>0 && b>0);
  cout<<”\n a>0 && b<0=”<<( a>0 && b<0);
  cout<<”\n a>0 || b<0=”<<(a>0 || b<0);
  cout<<”\n a<0 || b<0=”<<( a<0 || b<0);
  cout<<”\n!(a==b)=”<<!(a==b);
  cout<<”\n!( a<0 || b<0)=”<<!(a<0 || b<0);
  return 0;
}

Output

a>0 && b>0=1
a>0 && b<0=0
a>0 || b<0=1
a<0 || b<0=0
!(a==b)=1
!(a<0 || b<0)=1



Spread the love
Lesson tags: Logical and operator in C++, logical not operator in C++, logical operators in c++, logical or operator in C++
Back to: C++ Programming Notes
Spread the love