Pages

Wednesday, 9 May 2018

Logical Operators in C


Logical Operators in C


Nested if-else statement helps in creating multiple choices inside a program. But there are also some disadvantages of using them which are given below.
Indentation is most important while using nested if-else statements. But if we add 2 layer nesting inside on if-else block. Then you will notice that your program is creeping towards right. And it will make difficult to read that program.
Braces are used to show the scope of statements. There are chances that you may commit a mistake while writing those braces. One single mistake will fill your program with lots errors.
As there are multiple if-else statements so you also have to take care of matching the correct else block with if statement.
So these are some serious problems while writing nested if-else statements. But wait! It is not compulsory to use nested if-else statements every time. We can accomplish the same task by using Logical operators.

What are logical operators?
Basically C uses three logical operators which are AND (&&), OR (||) and NOT (!). I hope you must have learnt about the Boolean Algebra. These three operators are also used in that.

Remember while writing AND and OR operator, it should be written with two symbols which are && for AND and || for OR. Single symbol has completely different meaning in C programming.

So now lets take one example to understand the use of logical operators.

Question: Make a program to print the division of student. Take marks from the user. Calculate the percentage and calculate their division.


#include<stdio.h>

void main( )
{
 int  n1,n2,n3,n4,n5,perc;
 printf("Enter marks of student in five subjectsn");
 scanf("%d %d %d %d %d",&n1,&n2,&n3,&n4,&n5);
 perc=(n1+n2+n3+n4+n5)/5;

 if(perc>=60)
  printf ("You have got First division"); 

 if((perc >=50)&&(perc<60))  
  printf ("You have got Second division"); 

 if((perc>= 40)&&(perc<50))  
  printf("You have got Third division"); 

 if(perc<40)  
  printf("Sorry you are Fail");
#include<stdio.h>

void main( )
{
 int  n1,n2,n3,n4,n5,perc;
 printf("Enter marks of student in five subjectsn");
 scanf("%d %d %d %d %d",&n1,&n2,&n3,&n4,&n5);
 perc=(n1+n2+n3+n4+n5)/5;

 if(perc>=60)
  printf ("You have got First division"); 

 if((perc >=50)&&(perc<60))  
  printf ("You have got Second division"); 

 if((perc>= 40)&&(perc<50))  
  printf("You have got Third division"); 

 if(perc<40)  
  printf("Sorry you are Fail");
}