Logical Operator In C++ With Example

Logical Operator In C++ With Example

Logical Operators

The logical operators are used to combine relational expressions or relational conditions. The expression containing logical operators is called logical expression or logical condition.
It is also called compound condition or compound expression.
The output of a logical expression is also in logical form. Its value is either true or false. In C++, following logical operators are used:

i) &&  =======>> AND Operator
ii) ||      =======>> OR Operator
iii) !      =======>> NOT Operator

The && (AND) Operator


The && (AND) operator is used to combine two or more relational expressions. If all relational expressions are true then the output returned by the compound expression is false, the output is false.

For Example, if x=10 , y=15, z=5 then the compound expression  (x<y)  && (z = = 5) returns true because both the expressions (x< y) and (z = = 5)  are true. Similarly , the compound expressions (x>y)  && (z = = 5) and (x<y) && (z>x) will return false values.

Program:

Write a program to find out the largest no. from three gives numbers.

# include <iostream.h>
main ()
{
int a, b, c;
cout << "Enter first value";
cin >> a;
cout << "Enter 2nd value";
cin >> b;
cout << "Enter 3rd value";
cin >> c;
if ((a>b) && (a>c))
cout << "1st value is greater";
else
if (( b>a) && (b>c))
cout << "2nd value is greater";
else
cout << "3rd value is greater";
}

The || (OR) Operator:

The or operator is used to combine more than one relational expressions. If anyone of the given relational  expressions is true, the output will be true otherwise the output will be false.

For example:
if x=0, y=15 , z=5 then the compound expression (x>y) || (z = = 5) returns true because ( z= =5 ) is true.
Similarly, (x ! = y) || (x = = y) || (z>10) returns true because (x!=y) is true.
If all the relational expressions in the compound condition are false then output will be false.

The  ! (NOT) Operator

The ! (NOT) operator  is also known as the unary operator . It inverts the value returned by the relational  expression or the compound expression.

For example, if x=5 and y=10 then the logical expression  ! (x>y) returns true. It is because (x>y) returns false and the "!" (NOT) operator inverts the result into true.
Creative Commons License
Pakistan How by Tahira Aijaz is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.