FOR

FOR Loop Introduction

FOR loops, also known as counting loops, are one of the most useful loop structures in Computer Science. They allow the programmer to loop exactly as many times as they need.

FOR Loop Syntax

The basic FOR loop structure is:

for <NewLoopVariable> : <StartValue> .. <EndValue>
    %<Your Code Goes Here...>
end for

When you create a FOR loop, Turing creates a Loop Variable for you. This Loop Variable start off having a value equal to StartValue. Every time Turing hits a FOR loop's 'end for', it increases the Loop Variable by 1. The FOR loop runs until the Loop Variable is larger then EndValue. An example of this would be:

for iCounter : 1..5
    put iCounter..
end for

This would produce the following output:

12345

It is important to note that while you can use the loop variable for printing, you cannot change the loop variable. Also, StartValue should always be smaller then EndValue in this case.

FOR Decreasing Syntax

If you need a FOR loop to run backwards, you can do this by using the following syntax:

for decreasing <NewLoopVariable> : <StartValue> .. <EndValue>
    %<Your Code Goes Here...>
end for

This behaves the same as a normal FOR loop, but it runs backwards. For this to happen, ensure that StartValue is larger then EndValue. An example would be:
for decreasing iCounter : 5..1
    put iCounter..
end for

This would produce the following output:

54321

Nested FOR Loops

In some cases, it is essential for us to have one FOR loop inside another FOR loop. This is particularly useful for printing grids. The FOR loop syntax is exactly the same, but there is a second FOR loop before the first FOR loop's 'end for'.

for iRow : 1..5
    %Your Code Can Go Here...
    for iCol : 1..5
        %Your Code Can Go Here Too...
    end for
    %And It Can Even Go Here Too...
end for

For example, if we wanted a program that would show:

234
345
456

We could write:

for irow : 1 .. 3
    for icol : 1 .. 3
        put irow + icol ..
    end for
    put ""
end for
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License