Logical Operators

Logical Operators

Published by: Nuru

Published date: 21 Jun 2021

Logical Operators Photo

Logical Operators

  • Logical operators are used to compare or evaluate logical and relational expressions. The operands of these operators must produce either 1 (True) or 0 (False). The whole result produced by logical operators is thus either True or False.
  • Sometimes we need to ask more than one relational question at once.It let us combine two or more relational expressions into a single expression that evaluates to either true or false
  • It is also used in decision-making statements.
  • The below table shows the logical operators in C.
Operator Symbol Example
AND && exp1 && exp2 e.g.(num>100)&&(num%2==0)
OR || exp1 || exp2 e.g.(num<100)||(num%2!=0)
NOT ! !exp1 e.g.num!=5

Following table is C's logical operators in use:

Expression What it evaluates to
(exp1 && exp2) True(1) only if both exp1 and exp2 are true;
False(0) otherwise
(exp1 || exp2) True(1) either exp1 or exp2 is true;
False(0) if only both are false
(!exp1) True(1) if exp1 is false;
False(0) if exp1 is true
  • We can create expressions that use multiple logical operators. For example, to ask the question "Is x equal to 2, 3, or 4?" We can write : (x == 2) || (x == 3) || (x == 4)
  • It often provides more than one way to ask a question.
  • If x is an integer variable, the preceding question also could be written in either of the following ways:

1. (x > 1) && (x < 5)

2. (x >= 2) && (x <= 4)

Precedence of Logical Operators

  • Among the logical operators Not (!) has the highest precedence, AND (&&) has next highestandOR(||)haslowestprecedence.
  • The ! operator has a precedence equal to the unary mathematical operators ++ and --.
  • Thus, ! has a higher precedence than all the relational operators and all the binary mathematical operators.
  • The && and || operators have much lower precedence, lower than all the mathematical and relational operators, although, &&has a higher precedence than ||.
  • As with all of C's operators, parentheses can be used to modify the evaluation order when using the logical operators. Consider the following example:
  • We want to write a logical expression that makes three individual comparisons:

1. Is a less than b?       2. Is a less than c?         3. Is c less than d?

  • We want the entire logical expression to evaluate to true if condition 3 is true and if eithercondition 1orcondition 2istrue. Wecanwriteas a
  • However, this won't do what we intended. Because the && operator has higher precedence than ||, the expression is equivalent to a < b || (a < c && c < d) and evaluatestotrueif(a
  • So we need to write (a < b || a

Some examples

#include
#include
void main()
{
int a=10,b=5,c=20;
clrscr();
printf(“\n a %d”, (a printf(“\n a>b && b %d”, (a>b && b printf(“\n a %d”, (a printf(“\n a>b || b %d”, (a>b || b printf(“\n a>c || b>c => %d”, (a>c || b>c));
getch();
}