When we previously talked about conditions in if statements, we said that
conditions are built out of relational and logical operators. We
described the six relational operators that C provides for comparing numbers:
== != > < >= <=
But suppose you need to know if the value of the variable x is both
greater than zero and less than one? None of these relational operators by
itself can answer that question. What you need is to combine two conditions:
(x > 0.0) and (y < 1.0)
This is what logical operators can do for you. A logical operator
combines one or two conditions into a single new condition. C provides three
logical operators:
- ``&&'' (two ampersands) means and.
- ``||'' (two vertical bars) means or.
- ``!'' (an exclamation point) means not.
Let's look at an example. If you need to know if the value of the variable
x is between zero and one, inclusive, you would write this:
if ((x >= 0.0) && (x <= 1.0))
...
Now you try. Translate the following English questions into C conditions.
- Is the temperature temp greater than 32.0 and less than
212.0?
- Is the height not equal to zero?
- Is the absolute value of pos greater than 5.0?
Click here for the answers.
By the way, when you use ``&&'' or ``||'', be careful not to
write ``&'' or ``|'' instead! C has two other operators named
``&'' and ``|'', but they don't do the same things as ``
&&'' and ``||''.
Now let's return to the example that started this discussion. Can you write
a single if statement that determines whether or not a point (x, y, z)
is inside the unit cube?
Click here for the answer
We can use logical operators to simplify the multi-way if statement in
``block3.c''. See if you can figure out how before looking at our solution in
block4.c.
Joseph L. Zachary
Hamlet Project
Department of Computer Science
University of Utah