9.09.2011

Logical Operator

When we use if, for, while then use one condition at once time what happen if we examine condition more than one? In this case we use logical operators. So logical operators are used to combine two or more condition.
There are three types of  logical operators as following:
Operator symbol Name
&& Logical AND
|| Logical OR
! Logical NOT

LOGICAL AND OPERATOR ( && )

The condition is true if and only if both two expression are true otherwise condition false. The truth table of logical AND operators end of this chapter.

LOGICAL OR OPERATOR ( || )
 The condition is true if one of expression is true and condition will be false only if both expression are false. See example of || operator at end of this chapter.

LOGICAL NOT OPERATOR ( ! )

It reverse the expression i.e if the expression evaluates   to a non-zero value, then applying ! operator to it results into a 0 and vice versa. The final result (after applying ! ) 0 or 1 is considered to be false or true respectively.

Example of above three operators :
//following table con = condition.

con 1 Con 2 con 1 && con 2 con 1 || con 2 ! con 1 ! con 2
False False False False True True
False True False True True False
True False False True False True
True True True True False False

Some numerical example :
if(10>5 && 1000<2001)  // True
while( ; num>=1 || num<=100  ; ) // if num=1  True

Now some discuss of  NOT operator when we write condition if( 1 ! = 0 ) what is mean it? It is mean "one is not equal to zero", so is condition TRUE or False? It is true.

Let's understand following example :

if(sex!='M')
  printf("Person is Female");
else
  printf("Person is Male");

In above example evaluate first printf if condition is false otherwise evaluate second printf.

!(x<22) it is also we write (x>=22) // both are equal.

No comments:

Post a Comment