Java Reference
In-Depth Information
Self-Test Exercises
(continued)
24. What is the output produced by the following?
int
n = 10;
do
{
System.out.println(n);
n = n - 3;
}
while
(n > 0);
25. What output would be produced in Exercise 24 if the
>
sign were replaced with
<
?
26. What is the output produced by the following?
int
n = -42;
do
{
System.out.println(n);
n = n - 3;
}
while
(n > 0);
27. What is the most important difference between a
while
statement and a
do-while
statement?
The
for
Statement
The third and final loop statement in Java is the
for
statement
. The
for
statement is
most commonly used to step through some integer variable in equal increments. The
for
statement is, however, a completely general looping mechanism that can do any-
thing that a
while
loop can do.
For example, the following
for
statement sums the integers 1 through 10:
for
statement
sum = 0;
for (n = 1; n <= 10; n++)
sum = sum + n;
A
for
statement begins with the keyword
for
followed by three expressions in
parentheses that tell the computer what to do with the controlling variable(s). The
beginning of a
for
statement looks like the following:
for (
Initialization
;
Boolean_Expression
;
Update
)
The first expression tells how the variable, variables, or other things are initialized, the
second expression gives a Boolean expression that is used to check for when the loop
should end, and the last expression tells how the loop control variable or variables are
updated after each iteration of the loop body. The loop body is a single statement (typ-
ically a compound statement) that follows the heading we just described.