Java Reference
In-Depth Information
// Print the squares of 2 , 3 , and 4
int i= 2;
while (i != 5) {
System.out.println(i * i);
i= i + 1;
The while-loop consists of:
Style Note
13.2, 13.2.3
• The keyword while .
• The loop condition i!=5 , within parentheses.
• The repetend of the loop: the block { … }.
The loop condition can be any boolean expression, and the repetend can con-
tain any sequence of statements. Repetend means “the thing to be repeated”.
Note that the statements within the block are indented. This follows the conven-
tion that subparts of a statement are indented.
Execution of a while-loop can be described using the following flow chart :
According to the flow chart, execution begins by evaluating the loop condition.
If it is false , then execution of the loop terminates; if true , the repetend is exe-
cuted, and the process repeats, beginning with the test of the loop condition.
Each execution of the repetend is called an iteration of the loop. The first
iteration is iteration 0 , the second is iteration 1 , and so on. If the loop condition
is false initially, then zero iterations are performed during execution of the loop.
Activity 7-1.1
shows the actu-
al execution of
a loop, step by
Tracing execution of a loop
Generally, when executing a program by hand, we draw each variable as a named
box. When executing an assignment to x (say), we cross out the old value of x
and put in the new one. However, when first learning about loops (and, at times,
when looking for a hard-to-find error), it is helpful to draw the variables in a way
that exposes the order in which the assignments were made. We call this a tim-
ing diagram . We illustrate by showing how to execute the following loop:
int x= 0; int i= 3;
while (i != 5) {
x= x+i*i;
i= i + 1;
Search WWH ::

Custom Search