6. ITERATION - Part 1
One of the fundamental actions of computer code is to loop around itself. This has the advantage of re-using the same block of code but with a different set of conditions each time.
FOR ...... NEXT
This construct sets up a counter to count how many times around the loop the code has run, Once the end condition has been met, the loop finishes and the CPU carries on with the next block of code.
Example
FOR myloop_counter = 1 to 30 STEP 2 x = x + 1 Print (x) NEXT
The loop counter in this case is called 'myloop_counter'.
The starting value is 1 although it could be anything - even a negative number. The ending value is 30, so once the myloop_counter has incremented to this value the loop terminates.
The default increment is 1 which usually does not need stating, however, if a different increment is needed then the STEP keyword sets this value. In this case the increment is 2 so the loop will go around 15 times.
Note that a FOR .... NEXT loop will run at least once.
DO .... WHILE
Another construct for looping is the DO ..... WHILE loop
Example
DO Print (x) if printer = 'out of paper' then finish_loop = 'Time to end' WHILE finish_loop is NOT 'Time to end'
With this form of loop you are manipulating the condition to exit within the code itself. This is often handy when you need to test for a non-numeric condition.
In the example above, the code prints out a variable x, then something checks to see if the printer is out of paper. When it is, the variable 'finish_loop' is set to the terminating condition, otherwise the loop keeps on going around.
This kind of loop also executes at least once because the WHILE condition is not tested until the end of the first loop.
A very similar form is the REPEAT ...... WHILE loop which also tests for an end condition after running the code once.
Infinite loop
Note: you must be careful that the end condition will actually happen!
A very common coding error is to cause the end condition to never occur and you end up with an infinite loop.
For instance
FOR myloop_counter = 1 to 30 STEP 2 x = x + 1 Print (x) myloop_counter = 1 NEXT
In this case the myloop_counter is reset to 1 every time within the code, so it cannot end.
Challenge see if you can find out one extra fact on this topic that we haven't already told you
Click on this link: Using programming iteration FOR NEXT