Skip to content Skip to sidebar Skip to footer

The Do Until ¦loop Repetition Structure Tests a Condition for Falsity for Repetition to Continue

Introduction to Repetition Structures


Repetitive control structures, also referred to as iterative structures, are groupings of code which are designed to repeat a set of related statements. This repetition (or iteration) can repeat zero or more times, until some control value or condition causes the repetition to cease. We use iterative controls when we need to do the same task more than once, based upon some logical condition. While the terms repetition and iteration are very descriptive words, the common term to describe these control structures is loop. Loops consist of two logical parts; the condition (i.e. the logic that evaluates the condition), and the loop body (i.e. where the code integral to the loop is located). I categorize loops into two general categories:

  1. indeterminate loops
  2. determinate loops

The difference being that with a determinate loop structure, one can (normally) predict exactly how many times the loop will repeat; whereas with an indeterminate loop structure, this is not always the case. An indeterminate loop structure loops as long as a condition evaluates to some certain boolean value. Indeterminate loops should be used when the programmer does not know exactly how many times the iteration need occur. Logically however, both indeterminant and determinate loops can be written to be equivalent.

Beginning with indeterminate looping structures, there are two types to introduce:

  1. pre-test loops
  2. post-test loops

A pre-test loop evaluates its condition before any statements contained in its body are executed. Thus, a pre-test loop can execute its body a minimum of zero times, assuming the initial value of the condition evaluates to False. A post-test loop on the other hand, evaluates its condition after it executes all statements in its body. Thus, a post-test loop can execute its body a minimum of one time, even if the initial value of the condition evaluates to False. Below are diagrams representing of each type of loop:

When considering pre-test loops, the standard example is the Do-While loop. The general syntax of the Visual Basic Do-While can be viewed a couple of ways:

        Do While        condition        Do While        condition        [statement(s)]        [statement(s)]        statement affecting        condition        Loop        Loop      
The structure on the left above is technically correct syntax, but perhaps not logically so. Technically, a loop body can contain zero statements; but if that is the case, the loop will never terminate. A loop that never terminates is called an infinite loop, and typically is not a desirable event. The structure above on the right mandates at least one statement that will affect the condition, thus hopefully causing the loop to end. Once the loop ends, program execution will continue at the first statement following the end of the loop.

The condition in any loop must evaluate to a Boolean value; as always, either True or False. The condition in a loop will be similar to the logic and syntax used in an If-Then statement. That is, the condition will consist of relational and/or logical operators. It is the condition that is perhaps the most difficult part of a loop; if the logical condition is incorrect, there is little hope that the loop will produce the desired results. It is also of import that the condition which will cause the loop to terminate must occur. Looking at a Do-While loop structure whose task is to sum the numbers between 1 and 5, we can observe the following (note the numbers to the left are for descriptive purposes only):

        
  1. Dim intCount As Integer = 1
  2. Dim intSum As Integer
  3. Do While intCount <= 5
  4. intSum = intSum + intCount
  5. intCount = intCount + 1
  6. Loop
Looking closer at each numbered statement above:
  • statement 1 declares an Integer variable, intCount, and initializes it to 1. This will be used as our counter or control variable, which will allow termination of the loop.
  • statement 2 declares another Integer variable to be used to store our summary total (i.e. sum). It is not intialized, but recall any variable not specifically initialized is set to zero by VB.
  • statement 3 is the start of our Do-While loop construct. Note that our logical condition here is intCount <= 5. It should be understood that the condition intCount <= 5 must be True for the loop body to continue to execute.
  • statement 4 accumulates the value of intCount into intSum.
  • statement 5 increments the counter; it is this statement that will eventually cause our condition to be False.
  • finally, statement 6 is the formal end to the loop.
Below is a table of values for each variable as well as the corresponding Boolean condition as the loop iterates:

intCount intSum intCount <= 5 Comment
1 0 True initial values as loop entered
2 1 True start of pass 2
3 3 True start of pass 3
4 6 True start of pass 4
5 10 True start of pass 5
6 15 False loop terminates

As you can see from above, when the value of intCount becomes 6, the relational condition returns a False value, and loop execution terminates.

As stated previously, the difficulty with loops is the logic which is required to make them work correctly. Consider the following simple modification to statement 3 above:

        Do While        intCount < 5      
Do you notice the difference? This error is another example of a nasty "off by 1" error. Using only the less than operator, although it may not appear that different, will result in a value of 10. It should be clear that this will result in the summation of the numbers from 1 to 4, not 1 to 5.

Similarly, consider this simple modification:

        Do While        intCount = 5      
Do you notice this difference? Since intCount is initialized (by default) to zero and the incrementing statement being inside the loop, this will result in the loop body never getting executed. This logic error will result in a value of 0, which is perhaps even worse. Pay very close attention to the logical details when working with loops and relational operators!

When considering post-test loops, the standard example is the Do-Until loop. The general syntax of the Visual Basic Do-Until can be viewed a couple of ways:

        Do        Do        [statement(s)]        [statement(s)]        statement affecting        condition        Loop Until        condition        Loop Until        condition      
As above, the structure on the left above is technically correct syntax, but perhaps not logically so. Technically, a loop body can contain zero statements; but if that is the case, the loop will never terminate. Notice here the condition is checked at the bottom of the loop, thus the loop body will always be executed at least once. Looking at a similar Do-Until loop to sum the numbers between 1 and 5, we observe:
        
  1. Dim intCount As Integer = 1
  2. Dim intSum As Integer
  3. Do
  4. intSum = intSum + intCount
  5. intCount = intCount + 1
  6. Loop Until intCount > 5

Most of the logic here is similar to the Do-While loop above. However, notice the correlation between the relational operator in the Do-While and the one in the Do-Until. Do you understand this correlation?

When considering determinate loops, the standard example is the For-Next loop (note that this is also a pre-test loop). The general syntax of the Visual Basic For-Next is as follows:

        For        counter        =        start_value        To        end_value        [        Step        step_value        ]        [statement(s)]        Next        [        counter        ]      
This looping structure appears a bit more complicated than the other two, simply because there are more components. Looking at the components individually, we see:
  • counter - the control variable for the loop, initially set to start_value, and holding values through (and past) the end_value, as specified by the optional step_value. The data type of counter is usually Integer but can be any type that supports the >=, <=, +, and - operators.
  • start_value - the initial value for the counter. This value is assigned before the loop iteration begins.
  • end_value - the terminating value for the counter. This value will be the final value for the counter within the loop; but will be larger/smaller outside the loop, depending upon step_value.
  • step_value - optional, the amount by which counter is incremented each iteration through the loop. If omitted, the step_value defaults to 1. When specified, this value may be positive or negative.

As the execution of the For-Next loop begins, VB evaluates start_value, end_value, and step_value. The start_value is then assigned to the counter variable. Before execution of the For-Next body, the counter is compared to the end_value. If counter is already greater than (for a positive step_value or less than for a negative step_value) the end value, the For-Next loop terminates and control is passed to the statement following the Next statement; otherwise the statement block is executed. This algorithm for the For-Next loop can be summarized as follows:

  1. initialize counter variable to start_value
  2. evaluate counter <= end_value if positive step_value or 1
    evaluate counter >= end_value if negative step_value
  3. if step 2 returns True, execute body statements, if False terminate loop
  4. increment counter by step_value (or 1 if none specified)
  5. goto step 2

As with the above summation examples above, below is an equivalent For-Next loop:

        Dim        intCount        As Integer        Dim        intSum        As Integer        For        intCount = 1        To        5 		 	    intSum = intSum + intCount        Next      
which achieves and equivalent result. One important difference to note from the other two loop structures is that in a For-Next loop, the increment of the control variable happens automatically. That is, incrementing the counter variable is built in to the loop behavior (note this is step # 5 in the two loop examples above). This is commonly a confusing point for students.

As in the examples above, the value of intSum upon termination of this loop would be 15. However, it is important to look at the value intCount would have upon loop termination. As this loop will only terminate when intCount > 5, the value of that variable would then be 6. Any usage of this variable will result in using the value 6. This is a very important side effect of all loops in general.

Note you could also write the above For loop as:

        For        intCount = 5        To        1        Step        -1      
and achieve an equivalent result, however this may be logically more difficult to understand.

When looking at the following two For statements, we might ask the simple question "how many times will each loop, loop?"

  1. For intCount = -5 To 5
  2. For intCount = 0 To 15 Step 2
While we might be able to calculate the result using our fingers, a more accurate approach is by using the following formula to calculate exactly how many iterations a loop will perform:
        # iterations = Int          2        ((end_value - start_value) / step_value) + 1      
which when step_value = 1, simplifies to
        # iterations = end_value - start_value + 1      
Thus, in the example # 1 above, the number of iterations would be:
        (5 - -5) + 1 or        11      
and example # 2 would result in
        Int ((15 - 0) / 2) + 1, or        8      
Make sure you clearly understand how each of these results were found.

1 Note this step implies if start_value > end_value and step_value > 0, the For-Next loop will iterate zero times. The same is true for the logical inverse of this.

2 The Int function returns only the integer portion of its argument, never any decimal part. For example, INT (6.8) returns 6.



©2007, Mark A. Thomas. All Rights Reserved.

sawyerlartudied.blogspot.com

Source: https://homepages.uc.edu/~thomam/Intro_OOP_Text/Loops.html

Post a Comment for "The Do Until ¦loop Repetition Structure Tests a Condition for Falsity for Repetition to Continue"