Page 65 - Introduction to Programming with Java: A Problem Solving Approach
P. 65
2.7 if Statements 31
?
?
⎫ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢
⎬ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢
⎭
Do not do this!
Figure 2.6
Poorly structured flow of control
In addition to standardizing sequential, conditional, and looping control structures, structured program- ming also splits up large problems into smaller sub-problems. In Java, we put the solution to each sub-prob- lem in a separate block of code called a method. We’ll discuss methods in Chapter 5, but for now, we’ll focus on the three control structures shown in Figure 2.5.
2.7 if Statements
Apago PDF Enhancer
In previous sections describing print, assignment, and input statements, you saw examples of the sequential control structure on the left side of Figure 2.5. Now let’s consider the conditional control structure in the center of Figure 2.5. In going through a sequence of steps, sometimes you get to a “fork in the road,” at which point you must choose which way to go. The choice you make depends on the situation. More specifi- cally, it depends on the answer to a question. When a program has a fork in the road, programmers use an if statement to implement the fork. The if statement asks a question and the answer to the question tells the algorithm which way to go. More formally, the if statement contains a condition. A condition is a question whose answer is either yes or no. The answer to the condition’s question determines which statement ex- ecutes next. Here are three forms for the if statement:
“if”
“if, else” “if, else if”
Now let’s look at each of these three forms separately.
“if”
First, suppose you want to do either one thing or nothing at all. In that case, you should use the simple “if” form of the if statement. Here is its format:
if <condition> <statement(s)>
I
In
n
d
d
e
en
nt
ts
su
u
b
b
o
or
rd
di
i
n
n
a
at
t
e
e
s
st
ta
a
t
t
e
em
m
e
en
i
i
f
n
t
f
s
t
s
t
ta
a
t
te
e
m
me
en
nt
t
’
’s
s
h
h
e
e
a
a
d
d
i
in
n
g
g