C programming tutorial
Following are the three logical operators in C.
&&
||
!
&& is known as AND operator.|| is OR operator and ! is known as NOT operator.First two operators are used to combine multiple conditions in an if statement.NOT operator is used to reverse the result of the expression
on which it operate.
If && operator is used between multiple conditions the overall result will be true if and only if all conditions are true otherwise result will be false.
let us make a program whether a person is child,teenager or adult.
#include<stdio.h>
main()
{
int age;
printf("Enter age");
scanf("%d"&age);
if( (age>0) && (age<14) )
printf("child");
if ( (age>=14) && (age<18) )
printf("teenager);
if(age>18)
printf("adult");
}
'child' will be printed only if both conditions comes to be true.If any one of the conditon turns out to be false then whole thing will be treated as false.So 'child' will be only printed when age will be greater then zeroand less then 14.
If OR operator is used between multiple conditions the overall result will be true even if single condition evaluates to be true.Result will be false only when all conditions are false.
Let us make a program which tells is the entered number is vowel or not
#include<stdio.h>
main()
{
char a;
printf("Enter charecter");
scanf("%c",&a);
if( (a=='a') || (a=='e') ||(a=='i)'||(a=='o')'||(a=='u') )
printf("its vowel");
else
printf("Its not vowel");
}
In the above program if any one of the conditon inside will be satisfied overall result will be true.Hence 'Its a vowel will be printed'.
It reverses the logical value of a expression.If output of the expression comes to be true(1),it will make it false and if output comes as false(0) it will make it true
for example
(y<10) will be true if y will be less than 10 and false if y>10 .
But !(y<10) will be true if y is greater then 10 and false if y is less than 10.