Loops
A loop is a construct that enables a set of instructions to be executed more than once.
There are several loop constructions:
zero or more
These loops have the check at the begining of an iteration and as such will be executed 0 or more times. A while loop is an example.
one or more
These loops have the check at the end of the iteration and as such will be executed at least once. A do while loop is an example.
Loops with counters
These loops have a counter that counts from a certain number to an other number. The number can be used inside the loop (for example to access a field of an array).
Loops with an iterator
These loops use an iterator to loop through a certain structure.
Endless loops
These loops have no end. But of course nothing is forever, so the loop often contains a hidden mechanism.
Nested loops
If you understand single loops, nested loops can be difficult. But you need to focus on one loop at a time.
Lets take your example:
1
12
123
1234
12345
123456
Ok, lets first look at the lines.
- The first line has a single 1
- The second line counts from 1 to 2
- The third line counts from 1 to 3
- ...
Generally: the n th line counts from 1 to n.
Great, no we have the individual line. But let's now look at all lines.
- the first has n=1
- the second has n=2
- the third has n=3
- ...
Hm, so we can use the loop counter of the outer loop as the n in the inner loop:
for n = 1 to 6
s = ''
for i = 1 to n // use the loopcounter of the outer loop
s = s + char(i)
end for
out s
end for