08. AND, OR & NOT

By | September 22, 2021

Logical Operators

There are following logical operators supported by C++ language.

Logical operators are used to determine the logic between variables or values:

OperatorNameDescriptionExample
&& Logical andReturns true if both statements are truex < 5 &&  x < 10
|| Logical orReturns true if one of the statements is truex < 5 || x < 4
!Logical notReverse the result, returns false if the result is true!(x < 5 && x < 10)

Example

#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

Leave a Reply

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