Comparison Operators
Comparison operators allow us to compare two values against one another. A comparison returns a boolean result of either true or false. The table below lists each of the common comparison operators and their usages:
Operator | Usage |
> | Greater Than |
< | Less Than |
>= | Greater Than Or Equal To |
<= | Less Than Or Equal To |
== | Equal To |
!= | Not Equal To |
A Basic Comparison
In the following example, we compare two variables x
and y
. We store the result of this comparison in variable z
.
What will get printed to the screen? The above comparison, x > y, is evaluating if 10 is greater than 8. Because 10 is indeed greater than 8, z
is assigned a value of true. Thus, true
will get printed to the screen.
More Practice with Comparisons
Let's get a little more practice. Take a look at the following code segment below. Pay close attention to each comparison and the operator being used.
When we run this code, what boolean values (true or false) will get printed to the screen for variables t through z? What boolean values (true or false) will get printed to the screen for each of the boolComparison variables? See if you can figure it out on your own. The solution is given below.
Solution:
Our program prints out:
Comparison Operators in a Program
Suppose we want to write a program which restricts people under a certain height from riding on a roller coaster. For this particular roller coaster, people who are under 4 feet (48 inches) are not allowed on the ride. How would we do this?
After getting the potential rider's height in inches, we do a comparison to ensure that they are over 48 inches. The result of this comparison is then printed out.
Pitfalls
A common mistake is using =
when you actually want to use ==
. =
is used for assignment of variables whereas ==
is used for comparing the equality of two values.
For example, x = 5
stores the value 5
into the variable x
. However, x == 5
tests to see if the value 5
is equal to the variable x
and then returns either true or false. They are not the same thing!
Last updated