A more complex example

Now that we understand the simpler example, let us consider a slightly more complex example:


\begin{algorithm}
% latex2html id marker 93\begin{algorithmic}[1]
\STATE $x ...
...
\end{algorithmic} \caption{A loop that embeds another loop}
\end{algorithm}

The indentation shows how the statements are nested. Lines 6 and 7 are the most nested statements. They are nested within the prechecking loop that begins on line 5 and ends on line 8.

Note that the assignment statements on lines 4 and 9 are ``peers'' of the prechecking loop that begins on line 5 and ends on line 8.

Everything from line 4 to line 9 are nested inside the outer prechecking loop.

It may be helpful to show a diagram of this algorithm. Figure 1 represents the same logic in a trail-map format.

Figure 1: Graphical representation of algorithm 2.
\includegraphics{whilewhile}

Of course, no explanation is complete without a trace! Table 1 traces this algorithm.


Table 1: Partial trace of algorithm 2.
line# x y s comments
         
pre ? ? ? we know nothing about the variables
1 0 ? ? x is initialized
2 0 ? 0 s is initialized
3 0 ? 0 $x = 0 < 3$ is true, get into the outer loop
4 0 0 0 initialize y
5 0 0 0 $y = 0 < 2$ is true, get into the inner loop
6 0 1 0 y is incremented
7 0 1 1 s gets 0(s) + 1(y) + 0(x), loop back!
5 0 1 1 $y = 1 < 2$ is true, get into the inner loop
6 0 2 1 y is incremented again
7 0 2 3 s gets 1(s) + 2(y) + 0(x), loop back
5 0 2 3 $y = 2 < 2$ is false, exit inner loop
9 1 2 3 x is incremented, loop back to the beginning of the outer loop
3 1 2 3 $x = 1 < 3$ is true, get into the outer loop
... ... ... ...  


Tak Auyeung 2007-09-14