Logical Operators

There are many occasions when we face complex conditions to make a decision. This means that a decision depends upon more than one condition in different ways. Here we combine the conditions with AND or OR. For example, a boy can be selected in basket ball team only if he is more than 18 years old and has a height of 6 feet. In this statement a boy who wants to be selected in the basket ball team must have both the conditions fulfilled. This means that AND forces both the conditions to be true. Similarly we say that a person can be admitted to the university if he has a BCS degree OR BSC degree. In this statement, it is clear that a person will be admitted to the university if he has any one of the two degrees.
In programming we use logical operators ( && and || ) for AND and OR respectively with relational operators. These are binary operators and take two operands. These operators use logical expressions as operands, which return TRUE or FALSE.
The following table (called truth table) can be used to get the result of the && operator and || operator with possible values of their operands. It is used to explain the result obtained by the && and || operators.

Expression 1Expression 2Expression 1 && Expression 2Expression 1 || Expression 2
TrueFalsefalseTrue
TrueTruetrueTrue
FalseFalsefalseFalse
FalseTruefalseTrue

The && operator has a higher precedence than the || operator. Both operators associate from left to right. An expressions containing && or || is evaluated only until truth or falsehood is known. Thus evaluation of the expression (age > 18) && (height > 6) will stop immediately if age > 18 is false (i.e. the entire expression is false) and continue if age > 18 is true (i.e. the entire expression could still be true if the condition height > 6 is true ).

There is another logical operator that is called logical negation. The sign ! is used for this operator. This operand enables a programmer to ‘reverse’ the meaning of a condition. This is a unary operator that has only a single condition as an operand. The operator ! is placed before a condition. If the original condition (without the ! operator) is false then the ! operator before it converts it to true and the statements attached to this are executed.
Look at the following expression



Here the cout statement will be executed if the original condition (age > 18) is false because the ! operator before it reverses this false to true.

The truth table for the logical negation operator ( ! ) is given below.
Expression! Expression
truefalse
falsetrue

For previous lesson click here: If/else Structure
For next lesson click here: if/else Sample Program


the easiest way to learn programming
introduction to programming
Logical Operators

0 comments:

Post a Comment

 

introduction to programming Copyright © 2011-2012 | Powered by Blogger