In the last few sections, we have seen two ways to combine two or more if
statements. As the situation requires, we can
- nest if statements within one another, and we can
- write multi-way if that choose among more than two options.
Now let's look at another kind of situation.
Imagine that you're writing a program that simulates the Brownian motion of a
molecule within a volume of gas. Brownian motion is the random movement
of particles within a gas or a liquid. As the molecules of the gas or liquid
collide and bounce against each other, they move around on apparently random
paths through the medium.
Your program simulates the Brownian motion of one particular molecule inside a
volume of gas (for example, one helium atom inside a glass jar filled with
helium). Inside the program, the current position of the tracked molecule is
described by a three-dimensional point (x, y, z).
Your program needs to print a message when the gas molecule is within the unit
cube. That is, your program needs to print a message when:
- The value of X is between 0.0 and 1.0, inclusive; and
- The value of Y is between 0.0 and 1.0, inclusive; and
- The value of Z is between 0.0 and 1.0, inclusive.
How can you write this part of your program using if statements?
Click here for an answer.
Fortunately, there is an easier way to handle this situation. You can use
logical operators.
Joseph L. Zachary
Hamlet Project
Department of Computer Science
University of Utah