There are times when we want to repeat a certain portion of code several times. For small numbers of repeats, we could use something simple like Copy + Paste in our editor. However if we want to repeat an action many times, or even if we want to repeat infinitely, we need to use special techniques called loops. Using our GOTO function we have already seen a basic type of loop, but there are other types of loops that we can use. In some cases there are many ways to perform the same task.
We have already seen a simple loop using the GOTO function. Here is a good example:
LoopTop: ... 'code to repeat goes here GOTO LoopTop
Instead of having to create a new label and then jump to it, we can use a specialized structure called DO / LOOP that performs the same task, but is easier for people to read and understand.
DO / LOOPEdit
A DO / LOOP structure is an infinite loop, but it doesnt require us to create a label. To use a DO / LOOP, we write:
DO ... 'code to repeat goes here LOOP
FOR / NEXTEdit
If we have a certain piece of code that we want to repeat a finite number of times, we can't use an infinite loop, we need to use a counter variable to count the number of loops. We have already seen a basic implementation of this concept in the chapter on branches, but now we are going to look at a better structure for this, the FOR / NEXT loop. A FOR / NEXT loop allows us to do several things in a very simple and clean way:
- Initialize our counter variable
- Increment our counter variable every loop
- Check the counter variable to see if it has reached a final value. If it has reached the final value we exit the loop.
A FOR / NEXT loop looks like this:
FOR MyCounter = 0 TO 10 ... 'code here will be repeated 11 times NEXT
We can put one loop inside another loop. This is useful for many complicated programs that need to repeat sets of loops. Loops that are inside other loops are called nested loops. Also, the outer-most loop is typically called the parent loop, and the inside loops are called the child loops. Each child loop must have a different counter variable from it's parent loop, or the system will not work correctly.