Java Reference
In-Depth Information
Display 3.7
Demonstration of
while
Loops and
do-while
Loops
(part 2 of 2)
Sample Dialogue
First while loop:
Hello
Hello
Hello
Second while loop:
First do-while loop:
Hello
Hello
Hello
Second do-while loop:
Hello
A
while
loop can iterate its
body zero times.
A
do-while
loop always
iterates its body at least one time.
the loop is executed first and the Boolean expression is checked
after
the loop body is
executed. Thus, the
do-while
statement always executes the loop body at least once. After
this start-up, the
while
loop and the
do-while
loop behave the same way. After each
iteration of the loop body, the Boolean expression is again checked, and if it is
true
, the
loop is iterated again. If it has changed from
true
to
false
, then the loop statement ends.
The first thing that happens when a
while
loop is executed is that the controlling
Boolean expression is evaluated. If the Boolean expression evaluates to
false
at that
point, the body of the loop is never executed. It might seem pointless to execute the
body of a loop zero times, but that is sometimes the desired action. For example, a
while
loop is often used to sum a list of numbers, but the list could be empty. To
be more specific, a checkbook-balancing program might use a
while
loop to sum the
values of all the checks you have written in a month, but you might take a month's
vacation and write no checks at all. In that case, there are zero numbers to sum, so the
loop is iterated zero times.
executing
the body
zero times
Algorithms and Pseudocode
Dealing with the syntax rules of a programming language is not the hard part of solving
a problem with a computer program. The hard part is coming up with the underlying
method of solution. This method of solution is called an algorithm. An
algorithm
is
a set of precise instructions that leads to a solution. Some approximately equivalent
words to
algorithm
are
recipe
,
method
,
directions
,
procedure
, and
routine
.
An algorithm is normally written in a mixture of a programming language (in our
case, Java) and English (or other human language). This mixture of programming
language and human language is known as
pseudocode
. Using pseudocode frees you
from worrying about fine details of Java syntax so that you can concentrate on the
method of solution. Underlying the program in Display 3.8 is an algorithm that can be
expressed as the following pseudocode:
algorithm
pseudocode