Use Of Logical Operators
C allows usage of three logical operators, namely && ,|| and ! These are to be read as 'AND' ,' OR' and 'NOT' respectively.&&, || allows two or more conditions to be combined in an IF statement. Let us see how they are used in a program.Example:21
main()
{
int m1,m2,m3,m4,m5,per;
printf("Enter marks n five subjects");
scanf("%d%d%d%d%d",&ma,&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");
}
Advantages of this operators:
1. The matching of the IF's with their corresponding ELSES
gets avoided, since there are no ELSES in this program.
2.In spite of using several conditions, the program doesn't
creep to the right.
The else if Clause:
In this case every ELSE is associated with its previous If. The last ELSE goes to work only if all the conditions fail. Even in else if ladder the last ELSE is optional.
Note That the ELSE IF cause is nothing different. It is just a way of rearranging the else with if that follows it.This would be evident if you look at the following code:
if(i==2) | if(i==2)
printf("With you!........."); | printf("With you.....");
else | else if(j==2)
{ | printf(".....All the time");
if(j==2) |
printf("...... All the time");|
}
Example:22 /* Else if ladder demo*/
main()
{
int m1,m2,m3,m4,m5,per;
printf("Enter marks n five subjects");
scanf("%d%d%d%d%d",&ma,&m2,&m3,&m4,&m5);
per(m1+m2+m3+m4+m5)/5;
if(per>=60)
printf("First Division");
else if(per>=50)
printf("Second Division");
else if(per>=40)
printf("Third Division");
else
printf("Fail");
}
Example:23
main()
{
char gender,ms;
int age;
printf("Enter age,gender,Marital Status");
scanf("%d%c%c",&age,&gender,&ms);
if((ms=='M')||(ms=='U'&&gndeer=='M'&&age>30)
||(ms=='U'&&gender=='F'&&age>25))
printf("driver is insured");
else
printf("driver is not insured");
}
Explanation:
1. The driver will be insured only if one of the conditions enclosed in parenthesis evaluates to TRUE. 2. For the second pair of parenthesis to evaluate to TRUE, each condition in the parenthes is separated by '&&' must evaluate to TRUE.
3. Even if one of the conditions in the second parenthesis evaluates to FALSE, then the whole of the second parenthesis evaluates to FALSE.
No comments:
Post a Comment