Java Reference
In-Depth Information
Recall that the
*=
operator multiplies a variable by a certain amount (in this case,
2
).
Thus, this loop initializes an integer variable called
number
to
1
and then doubles it
while it is less than or equal to
200
. On the surface, this operation is similar to using
an
if
statement:
int number = 1;
if (number <= 200) {
number *= 2;
}
The difference between the two forms is that the
while
loop executes multiple
times, looping until the test evaluates to
false
. The
if
statement executes the dou-
bling statement only once, leaving
number
equal to
2
. The
while
loop executes the
doubling statement repeatedly, with
number
taking on the values
1
,
2
,
4
,
8
,
16
,
32
,
64
,
128
, and
256
. The loop doesn't stop executing until the test evaluates to
false
. It
executes the assignment statement eight times and terminates when
number
is set to
the value
256
(the first power of
2
that is greater than
200
).
Here is a
while
loop containing two statements:
int number = 1;
while (number <= max) {
System.out.println("Hi there");
number++;
}
This
while
loop is almost the same as the following
for
loop:
for (int number = 1; number <= max; number++) {
System.out.println("Hi there");
}
The only difference between these two loops is the scope of the variable
number
.
In the
while
loop,
number
is declared in the scope outside the loop. In the
for
loop,
number
is declared inside the loop.
Suppose you want to find the smallest divisor of a number other than 1. Table 5.1
gives examples of what you are looking for.
Here is a pseudocode description of how you might find this value:
start divisor at 2.
while (the current value of divisor does not work) {
increase divisor.
}
Search WWH ::
Custom Search