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: Below is a table of values for each variable as well as the corresponding Boolean condition as the loop iterates:

intCountintSumintCount <= 5Comment
10 Trueinitial values as loop entered
21 Truestart of pass 2
33 Truestart of pass 3
46 Truestart of pass 4
510 Truestart of pass 5
615 Falseloop 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:

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 = Int2((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.


Next Section: Fun With Strings Table of Contents


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