Logical Operators
There are following logical operators supported by C++ language.
Assume variable A holds 1 and variable B holds 0, then:
Operator Description Example
&& Called Logical AND operator.
If both the operands are
non-zero, then condition
becomes true. (A && B) is false.
|| Called Logical OR Operator.
If any of the two operands
is non-zero, then condition
becomes true. (A || B) is true.
! Called Logical NOT Operator.
Use to reverses the logical
state of its operand. If a
condition is true, then
Logical NOT operator will
make false. !(A && B) is true.
Try the following example to understand all the logical operators available in C++.
Copy and paste the following C++ program in test.cpp file and compile and run this program.
#include <iostream>
using namespace std;
main()
{
int a = 5;
int b = 20;
int c ;
if ( a && b )
{
cout << "Line 1 - Condition is true"<< endl ;
}
if ( a || b )
{
cout << "Line 2 - Condition is true"<< endl ;
}
/* Let's change the values of a and b */
a = 0;
b = 10;
if ( a && b )
{
cout << "Line 3 - Condition is true"<< endl ;
}
else
{
cout << "Line 4 - Condition is not true"<< endl ;
}
if ( !(a && b) )
{
cout << "Line 5 - Condition is true"<< endl ;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
Line 1 - Condition is true
Line 2 - Condition is true
Line 4 - Condition is not true
Line 5 - Condition is true
No comments:
Post a Comment