The first two logical operators, && and , never appear by themselves. They typically go between two or more relational tests. Table 2.9 below shows how each logical operator works. These are called the truth table because they show how to achieve true result from an if statement that uses these operators.
The AND (&&) Operator |
True AND True =True |
True AND False=False |
False AND True=False |
False AND False=False |
The OR () Operator |
True OR True=True |
True OR False=True |
False OR True=True |
False OR False=False |
The NOT (!) Operator |
NOT True =False |
NOT False=True |
The true and false on each side of the operators represent relational if
test. The following statements are examples of the logical operators
if((a<b) && (c>d)) cout <<"It is true when a<b and at the same time
c>d";
The variable a must be less than b and at the same time c must be greater than d
in order for the cout to execute. Another example is shown here to demonstrate
the NOT operator,
if(!(grade<70)) cout << "student pass the course";
If the grade is greater than or equal to 70 (equivalent to say not less than 70), cout will execute.
Notice that the overall formate of the if statement is retained when you
use the logical operators, but the number of conditions is expanded to include
more than one condition. You even can have three or more conditions connected by
the logical operator in the same if statement.
Example
/* This program tests if the year entered by the user is a summer
Olympic year, U.S. Census year or both (Olympic occurs every 4 years and Census
every 10 years) */
#include <iostream.h>
main()
{
int year;
cout << "Enter a year";
cin >> year;
if(((year%4)==0)&&((year%10)==0)) cout <<"Both Olympic and US Census";
else if((year%4)==0) cout <<" Summer Olympic Only";
else if((year%10)==0)) cout << "US Census Only";
else cout << "Neither the Olympic nor the US Census";
return 0;
}