Logical Operators in C

There are several things to note about these logical operators. Most obviously, two of them are composed of double symbols: || and &&. Don’t use the single symbol | and &. These single symbols also have a meaning. They are bitwise operators

Example of Logical operators in C

main( ) 
{ 
 int m1, m2, m3, m4, m5, per ; 
 printf ( "Enter marks in five subjects " ) ; 
 scanf ( "%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5 ) ; 
 per = ( m1 + m2 + m3 + m4 + m5 ) / 5 
if ( per >= 60 ) 
 printf ( "First division" ) ; 
 if ( ( per >= 50 ) && ( per < 60 ) ) 
 printf ( "Second division" ) ; 
 if ( ( per >= 40 ) && ( per < 50 ) ) 
 printf ( "Third division" ) ; 
 if ( per < 40 ) 
 printf ( "Fail" ) ; 
} 

As can be seen from the second if statement, the && operator is used to combine two conditions. ‘Second division’ gets printed if both the conditions evaluate to true. If one of the conditions evaluate to false then the whole thing is treated as false.

Two distinct advantages can be cited in favour of this logical operators programme:

  • The matching (or do I say mismatching) of the ifs with their corresponding elses gets avoided, since there are no elses in this program
  • In spite of using several conditions, the program doesn’t creep to the right. In the previous program the statements went on creeping to the right. This effect becomes more pronounced as the number of conditions go on increasing. This would make the task of matching the ifs with their corresponding elses and matching of opening and closing braces that much more difficult

The else if Clause in logical operators

There is one more way in which we can write program for.this involves usage of else if blocks

/* else if ladder demo */

main( ) 
{ 
int m1, m2, m3, m4, m5, per ; 
per = ( m1+ m2 + m3 + m4+ m5 ) / per ; 
if ( per >= 60 ) 
printf ( "First division" ) ; 
else if ( per >= 50 ) 
printf ( "Second division" ) ; 
else if ( per >= 40 ) 
printf ( "Third division" ) ; 
 else
printf ( "fail" ) ; 
} 

Table of logical operators in c

OperatorsType
!Logical NOT
* / %Arithmetic and modulus
+ –Arithmetic
< > <= >=Relational
== !=Relational
&&Logical AND
||Logical OR
=Assignment
Table of logical operators in c

The following figure summarizes the working of all the three logical operators

logical operators
logical operators

Leave a Comment