Thursday, 25 September 2014

Logical Operators in C++

18:02


Explanation
The logical operators are used to logically combine, compare Boolean conditions or expressions.
The following table lists the operators.

Operator
Action
!
NOT
&&
AND
||
OR

 


                                                                                   

 Details:


 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.



Logical AND
Example:
#include <iostream>
using namespace std;
int main()
{

cout << "Enter a number: ";
int nValue;
cin >> nValue;
if (nValue > 10 && nValue < 20)
cout << "Your value is between 10 and 20" << endl;
else
cout << "You value is not between 10 and 20" << endl;
return 0;
}
Logical OR
Example:

#include <iostream>
int main()
{
using namespace std;
cout << "Enter a number: ";
int nValue;
cin >> nValue;
if (nValue == 0 || nValue == 1)
cout << "You picked 0 or 1" << endl;
else
cout << "You did not pick 0 or 1" << endl;
return 0;
}



Logical NOT
Example:
int x = 5;
int y = 7;
if (!(x == y))
cout << "x does not equal y";
else
cout << "x equals y";
Another Example:

#include <iostream>
using namespace std;
int main ()
{
int a =5;
int b =20;
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;

}

Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

0 comments:

Post a Comment

 

© 2013 All in One. All rights resevered. Designed by Templateism

Back To Top