C++ Logical Operators

October 05, 2015 Posted by WithU Technologies




Operator


Symbol


Example


Conditional AND


&&


x&&y


Conditional OR


!


!(a&&b)


Bitwise AND


&


a&b


Bitwise OR


|


x|b


NOT


||


a||b


Exclusive OR


^


a^b



Logical operators use conditional statements and then they return true or false in results based on the state of the variable.

Conditional AND Operator:

·         Conditional AND works on two condition always as shown below:



x&&y


True


True


True


True


False


False


False


True


False


False


False


False




Example:

#include <iostream>
using namespace std;

int main(){

int age=19;    // integer variable initialized

if (age>=18 && age<=21){   // Two conditions are defined along with the conditional AND Operator in between

       cout<<"You are eligible for Indian Army"<<endl;  // If both the condition are found to be true, then this statement will be executed

  } 

}

Conditional OR Operator:

·         Conditional OR gives you a true result if anyone of the given condition is true as shown below:



x||y


True


True


True


True


False


True


False


True


True


False


False


False



Example:

#include <iostream>
using namespace std; 

int main(){

float height=5.4;     // float variable initialized

int age=19;           // integer variable initialized

if (height>=5.5 || age>=18){   // Two conditions are defined along with the conditional OR Operator in between

       cout<<"You are eligible for this JOB"<<endl;  // If any one of the condition is found to be true, then this statement will be executed

  } 

}


NOT Operator:
·         Not Operator is actually used to complement the values. It will give you the opposite of the value which you provided.



!(x&&y)


True


True


False


True


False


    True


False


True


True


False


False


True



Example:

#include <iostream>
using namespace std; 

int main(){ 

int age=29;    // integer variable initialized 

if (!(age>=18 && age<=21)){   // Two conditions are defined along with the conditional AND Operator in between. But Not operator makes it opposite

       cout<<"You are not eligible for Indian Army"<<endl;  // If both the condition are found to be true, then this statement will be executed

  }

}

Exclusive OR Operator:

·         The syntax for exclusive OR is ((x||y) && !(x&&y) as shown below:



XOR


True


False


False


True


True


True


True


True


True


False


True


False



 Example:

#include <iostream>
using namespace std;

int main(){ 

int a=19;    // integer variable initialized 

if (a==18 ^ a<21) {   // Two conditions are defined along with the conditional AND Operator in between. But Not operator makes it opposite

       cout<<"This is an Exclusive OR Operator"<<endl;  // If both the condition are found to be true, then this statement will be executed

  } 

}