next up previous
Next: Activity Up: If Statement Previous: The if-else-if Ladder

Logical Operators

There may be times when you need to test more than one set of variables. You can combine more than one rational test into a compound condition. for example you want to test the case at which a=b and c=d to print an output. To perform such operations you will need to use the C++ logical operators. Table 2.8 below shows the C++ operators.
 

 
Table 2.8: Logical Operators
Operator Meaning
&& AND
$\parallel$ OR
! NOT


The first two logical operators, && and $\parallel$, 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.


 

 
Table 2.9: Truth Table
The AND (&&) Operator
True AND True =True
True AND False=False
False AND True=False
False AND False=False
The OR ($\parallel$) 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;
}


next up previous
Next: Activity Up: If Statement Previous: The if-else-if Ladder
Yousef Haik
2/23/1998