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.


Logical Operators in C - Output


  • In the initial steps it is asked to enter student’s marks. After that I have calculated the percentage of the student based on the marks. Now I have to check the division of student.
  • Now in the first if statement I have given the condition if (perc>=60)  it will check if the percentage is greater than 60 then it will print the message “You have got first division”.
  • Now in the next if statement I have written the condition if ((perc>=50) && (perc<60)). So basically there are two condition inside it and they are joined through logical operators. Remember the statements under this if block will only execute when both the conditions is true because they are joined with AND operator.
  • Similar structure is adopted in the next if statement too.
  • In the last if statement percentage is checked whether it is less than 40. If it turns out to be true. Then it will display the message “Sorry you are fail”.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.