Logical Operators Example
//logical_ex.cpp
//logical operators example
//Note: there are three examples below -- study each example!
#include <iostream>
using namespace std;
int main()
{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//logical and (&&)
int x, y; //variable declarations
x = 7; //initialize variables
y = -5;
cout << "\nx is 7 and y is less than 0?";
// test for both conditions being true (&&)
if (x==7 && y < 0)
{
cout << "\nBoth conditions have been met.\n\n ";
}
else
cout << "\nSorry, both conditions are not met.\n\n\n";
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//logical or
int a, b; //declare two more variables
a = 3; //initialize variables
b = 78;
cout << "\nNew Example (2): \n";
cout << "\na is greater than 0 or b is less than 0\n";
//test for conditions
if (a >0 || b < 0)
{
cout << "One of the two conditions has been met!\n\n\n";
}
else
{
cout << "Neither of the two conditions has been met!\n\n\n";
}
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//multiple tests
int g, h,i,j; //declare more variables
g = 0; //initialize variables
h = 100;
i = -99;
j = 35;
cout << "\nNew Example (3): \n";
if ((g ==0 && h >50) && (i < 0 || j < 0)) //note extra parentheses!
{
cout << "Whew. Something met the test\n";
cout << "Can you believe it?\n";
}
else
cout << "\nNothing fits!";
return 0;
} //end of main