Java Reference
In-Depth Information
In a timing diagram, we draw the variables in a vertical column, separated
by a horizontal line; next to each variable, we place its initial value:
x 0
i 3
Now, we begin executing the loop. Whenever an assignment is executed, we
draw a vertical line to the right of the last value written and write in the new
value of the variable to the right of the line. For example, with the above loop,
because the condition i!=5 is true (since i is 3 ), the repetend is executed. First,
x is assigned the value 9 , yielding:
x 0 9
i 3
Then, the assignment to i is executed, yielding:
x 0 9
i 3 4
The loop condition is evaluated again; it is true , so the repetend is again exe-
cuted. Below, to the left, we show the trace of the variables after assigning to x
and, to the right, after assigning to i .
x 0 9 25
i 3 4
x 0 9 25
i 3 4 5
The loop condition is evaluated again. Because it is false (since i now has the
value 5 ), the loop terminates.
Tracing the values of variables in this fashion has the advantage that we see
clearly the order in which the variables were assigned and the values on which
the evaluation of each expression depends. If we feel we may have made a mis-
take (which happens more often than most programmers like to admit), we can
more easily go back and rectify it.
Self-review exercises
SR1 . Write down the syntax of the while-loop.
SR2 . Draw the flow chart of a while-loop.
SR3 . Draw timing diagrams for the following loops.
(a) x= 1; i= 1;
(b) x= 1; i= 3;
while (i != 4) {
while (i != 0) {
x= x * i;
x= x * i;
i= i + 1;
i= i - 1;
Search WWH ::

Custom Search