DEV Community

Mehfila A Parkkulthil
Mehfila A Parkkulthil

Posted on

Day 8 : C++Language| Logical Operators

Logical Operators

The three most commonly used logical operators are AND, OR, and NOT

AND (&&)

This operator requires that all connected conditions be true for the overall statement to be true.

For instance, in programming, if A and B represent conditions, A AND B returns true only if both A and B are true.

#include <iostream>
using namespace std;

int main() {
  int x = 6;
  int y = 4;

  cout << (x > 3 && x < 10); 

// returns true (1) because 6 is greater than 3 AND 4 is less than 10 .

 //since both statement are true , result will be true satisfying and operator

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

OR ( || )

This operator allows for flexibility—only one of the connected conditions must be true.

In the statement A OR B, the result will be true if either A or B (or both) is true.

#include <iostream>
using namespace std;

int main() {
  int x = 5;
  int y = 3;
  cout << (x > 1 || x < 3);

 // returns true (1) because one of the conditions are true
 (5 is greater than 1, but 5 is not less than 3)

  return 0;

}
Enter fullscreen mode Exit fullscreen mode

NOT (!)

NOT inverts the truth value of a single condition.
If A is true, then NOT A will be false, and vice versa.

#include <iostream>
using namespace std;

int main() {
  int x = 6;
  int y = 4;

  cout << !(x > 3 && x < 10); 
 // returns false (0) because ! (not) is used to reverse the result

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Uses of logical operators

They are implemented in conditional statements, loops, and algorithms to enable computers to make decisions.
For example, imagine an e-commerce platform where discounts are applied only if a customer is both a loyalty member AND has spent over a certain amount.


Logical operators will be explained in detail while learning loops


Previous Blogs

Top comments (0)