﻿ TLWNN Tutorial Lesson 6: Control Flow Techniques

# Lesson 6

## Controlled Looping

We have seen that procedures can be stored on the stack, both to reuse code and to implement an infinite loop.  However, most loops in the real world aren't infinite.  As such, we need a means of breaking out of these loops.

Let's look at a for loop first.  It is necessary to have two library procedures to hand: that which performs subtraction and that which performs a conditional.  These must be manipulated in order to increment (or decrement, which is slightly simpler) the counter and check for the terminating condition.

``````Example twelve
A simple repetition
!<<<@@>
Output 100 asterisks
[42!
\*\>1>! decrement the counter
*\[]<<<*>>\1>! check for termination
*! now do it again ]
*!
``````

Notice how, by adding the words "`Output`" and "`asterisks`" as comments, I have made this code self-documenting.

A similar technique can be used to create a do-while loop.  Just replace the decrement and check code with something that tests the condition you want to test.

This technique produces a test-after loop, i.e. one iteration will always be done before the condition is first tested.  A test-before loop is slightly more complex to write, as you will need to either duplicate the testing code or separate the looping condition from the loop body.  The following example demonstrates the duplication technique:

``````Example thirteen
A test before loop
!<<<@@>
Output 0 asterisks
[42!
\*\>1>! decrement the counter
*\[]<<<*>>\1>! check for termination
*! now do it again ]
>*\[]<<<*>>\1>!
*!
``````

This in itself is a rather long-winded null program, but the point is that it's a modification of the previous example to work even if 0 is given as the number of iterations.

## Selection

We have seen how a library procedure can be used to compare two numbers and take different action depending on which is smaller.  The method doesn't, however, distinguish the case that both numbers are equal from the case that the number on the main stack is the greater of the two.  If you want an equality comparison, or even to create a three-way selection, you will need to perform two comparisons.

More details will come soon!