In addition to the arithmetic operators, C++ provides a variety of
other operators including six relational operators. A relational
operator comparess two values and produces a boolean
value true
or false
indicating their relationship.
==
equality, returns true if and only if its operands are equal !=
inequality, returns true if and only if its operands are different <
less-than, returns true if and only if its left operand is less than its right operand >
greater-than, returns true if and only if its left operand is greater than its right operand <=
less-than-or-equal-to, returns true if and only if its left operand is not greater than its right operand >=
greater-than-or-equal-to, returns true if and only if its left operand is not less than its right operand
In C++, a boolean value is represented by the bool
type, so
these operators produce a bool
value. They are called the
relational operators because they are used to determine the
relationship between two values.
Add the following statement to your program to output these boolean values:
cout << "true is " << true << "\n" << "false is " << false << endl;Compile and execute your program.
Question #3.4.1: What does your program display for this output statement?
With your version of C++, you may actually see the boolean values
true
and false
output as words on the screen.
However, it is more likely that you will see integer values, probably
0
for false
and 1
for true
. In C++, 0 is interpreted as false and
any non-zero value as true (although most compilers use the
value 1).
Now insert
<< boolalpha
after cout
in the preceding output statement. Then compile
and execute your program.
Question #3.4.2: What does your program display for this modified output statement?
Now modify your program so that it
i
and j
from the keyboard.i
and j
using each of the relational operators listed above.i < j
in an output expression.
(We'll see why this is necessary in another experiment.)
Compile and execute your program.
Question #3.4.3: Find values fori
andj
in each row to make the indicated relationship true:
Relational Expression i
j
a. i < j
b. i <= j
c. i == j
d. i != j
e. i >= j
d. i > j
Use your program to confirm your values.