RELATIONAL AND LOGICAL OPERATORS

LOGICAL OPERATOR MEANING EXAMPLE
= = equal to k= =1
> greater than m > 2
< less than k < m
>= greater than or equal to m >= p
<= less than or equal to p <= m
!= not equal to k != m
The relational operators are used for BOOLEAN comparisons which enable a programmmer to use decision control instructions such as "if".


These operators are used to show the relationship between two quantities. The quantities may be variables, constants or functions, but they only have two values:


TRUE OR FALSE

ANY COMBINATION OF RELATIONALS MAY BE USED:

Example: The following program checks the user input of a number between 1 and 100 to see if the number entered is in the top or bottom 10%


#include isotream.h

int main( )
{
float number; //user input

cout<<"\n\n";
cout<<give me a number from 1 to 100";
cin number;

if(((number >= 1.0) && (number <=10.0)) || ((number>=9.0) && (number <= 100.0)))
cout<<"You gave me a number in the top or bottom 10%
}


You notice in this program that the symbols "&&" and "| | " were used. These are called LOGICAL OPERATORS.

Sometimes you need to make more than two comparisons to obtain the desired results. C++ provides three such operators that give the programmer more opportunity to make these larger comparisons.


RELATIONAL OPERATOR MEANING EXAMPLE
&& and (j= =1 && k= =2)
| | or (j= =1 | | k= =2)
! not! result= !(j= =1 && k= =2)

You can mix logical operators in statements as long as you understand the order in which the logical operators will be applied.
The "not" (!) operator is applied first, then the "and" (&&) and lastly the "or" ( | |). You must also use the brackets carefully as to not confuse the logic of the operation

BACK TO PROGRAMMING SECTION