Operators for logical use – Computer Sir Ki Class Code Learning #CPP#1739    ## Operators for logical use

Testing the use of logical operators like not, and and or operators.

## Learning Objectives

• Learning of logical operators like not (!), and (&&) or (||) operator.

## Source Code

 #include using namespace std; int main() { int a=10, b=0; if(!b) cout<<"! tested"<

## Run Output

``````! tested
&& tested
|| tested``````

## Code Understanding

int a=10, b=0;
Initialisation of variables is being done so that logical conditions can be tested.

if(!b) cout<<“! tested”<<endl;
Here we are making not of b, which is true as b has been initialised to 0 so not of b would be non-zero, hence if condition will be true.

if(a && !b) cout<<“&& tested”<<endl;
Here a is being tested for true and !b is also being tested for true. Since both conditions are true so the required matter would be printed.

if(a || b) cout<<“|| tested”<<endl;
Here either a being true or b being true is being tested. If any one is true then result will be printed. Since in this case a is not zero, so it is true and b is 0 so it is not true. But one condition is true so whole expression will be treated as true and if condition will do its job of printing the subsequent expression.

## Notes

• Notice that ! operator works on one value only while && and || operators require two values on each side, Thus we can also call ! operator as unary logical operator and && and || binary logical operator

Suggested Filename(s): operator-logic.cpp, logical-op.cpp

CSKC| Created: 16-Dec-2017 | Updated: 28-Aug-2018|

×