CSCI 201 Study Aid: Equality and Relational Operators

Equality and Relational Operators

Most programs make decisions based on the truth or falsity of some condition. If the condition is met, i.e:, the condition is true, some action is taken, or if the condition is not met, i.e.:, the condition is false, another action is taken.

Conditions can be formed by using the equality and relational operators summarized in the table below:

C++ equality
or relational
operator
Example of
C++ condition

Meaning of
C++ condition

== x == y x is equal to y
!= x != y x is not equal to y
> x > y x is greater than y
< x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y

The result of an equality or relational operator is either true (non-zero) or false (zero). The computer returns as a result of a comparison a true value or a false value which may then be tested using "control structures" which will be covered in the topics that follow.


Example 1:

The following program will display the results of each equality and relational operator using the cout object. A true result is normally any non-zero value while a false result will be displayed as zero:

Run the program below to see the results displayed.

#include <iostream.h>

main()
{

int x = 10;
int y = 5;
int z = 10;


// Show the results of the operators ...

cout << "x = " << x << endl;
cout << "y = " << y << endl;
cout << "z = " << z << endl << endl;

cout << "The TRUE  expression ( x == z ) evaluates to " << ( x == z ) << endl;
cout << "The TRUE  expression ( x != y ) evaluates to " << ( x != y ) << endl;
cout << "The TRUE  expression ( x  > y ) evaluates to " << ( x > y  ) << endl;
cout << "The FALSE expression ( x  < z ) evaluates to " << ( x < z  ) << endl;
cout << "The TRUE  expression ( x >= y ) evaluates to " << ( x >= y ) << endl;
cout << "The FALSE expression ( x <= y ) evaluates to " << ( x <= y ) << endl;
cout << "The TRUE  expression ( y < x < z ) evaluates to " << ( y < x < z ) << endl;

return 0;

}