Saturday, October 20, 2012

Use of pre-test loops

As discussed in class Thursday, in QBASIC, you have the option of writing pre-test or post-test loops. A pre-test loop is one in which the condition to stop the repetition is checked before the body of the loop is executed, therefore, the minimum number of iterations is zero. A post-test loop is one in which the loop termination condition is tested after the first execution of the loop's body; the minimum number of iterations is one.

Let's look at some source code for pre-test loops.

This is the syntax for a DO WHILE...LOOP

DO WHILE c
     ' BASIC code statements here
LOOP

where
c = a condition is which must be met
    in order to halt repetition


Here is a code example

The loop control variable, fg is declared and assigned an initial value before the loop. Before executing any iterations of the loop body, the condition is tested. In this case, the condition is fg <= 15. As long as the value of fg is less than or equal to 15, the body of the loop will run. Notice that the value of the loop control variable is changed inside the loop: fg = fg + 1.

Another way to get exactly the same output is by using the DO UNTIL...LOOP.

DO UNTIL c
     ' BASIC code statements here
LOOP

where
c = a condition is which must be met
    in order to halt repetition


In this instance, the loop termination is when fg > 15 since we are using the UNTIL keyword.

Yet another way to generate the identical output with a pre-test loop is to employ the WHILE...WEND loop.

WHILE c
     ' BASIC code statements here
WEND

where
c = a condition is which must be met
    in order to halt repetition


All three loops shown produce the same output