More complex decision making

 Hey, Guys today we are going to learn some "More complex decision making" everyday we all face situations where the action that we carry out is based on multiple conditions. In this topic we explores the use of logical operators and one more type of operators called conditional operators.



Use of logical operators- Checking Ranges:-


Basically C programming allows usage of three logical operators, namely, &&, || and !. WE read this as 'AND', 'OR' and 'NOT' respectively.

Out of this && and || operators allow two or more conditions to be.



Let's learn this with an example:-


Below the given program give's us the division of students.



#include <stdio.h>
int 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)*100/500;
 if (per>=60)
   printf ("First division\n");
 else
 {
    if (per>=50)
      printf ("Second division\n");
    else
    {
        if (per>=40)
          printf ("Third division\n");
        else 
          printf ("Fail\n");
    }
   }
    return 0;
}






If you observe that program you see the use of nested if-elses. This program works fine but it has three disadvantages:


(a) As the number of conditions go on increasing the level of indentation also goes on increasing.


(b) It is difficult to match the corresponding ifs and elses.


(c) It is difficult to match the corresponding pair of braces.



The else if clause:-


Let us rewrite the program again:-


/*else if ladder demo*/
if (per>=60)
  printf ("First division\n");
else if (per>=50)
  printf ("Second division\n");
else if (per>=40)
  printf ("Third division\n");
else
  printf ("fail\n");





Using of   if-else if-else reduces the indentation of the statements. Here the last else goes to work only if all conditions fail.



This figure summarizes the working of all the three logical operators.





This figure summarizes the Hierarchy of operators.



Comments

Popular posts from this blog

C-programming Introduction (Notes).

My Resume / Achievements.

All about hacking.