Back to DFS's Turing Page


The Simplest for Loop

When we want to execute a sequence of instructions a specific number of times, it is possible to set up and use one of the basic loops, such as the beginning-exit loop below. See the The beginning-exit & end-exit Loops page.

% Print the first five Natural numbers
num := 1
loop
   exit when num >= 5
   put num
   num := num + 1
end loop

For a situation such as this, Turing provides a programming short-cut known as the for loop. The one following performs the same task as the loop above, but uses only three lines of code.

for num : 1 .. 5
   put num
end for

The for statement specifies both the initialization of the counter and the maximum value that it may have during the execution of the loop.

In Turing, the for statement also checks to make sure the value of the counter does not exceed the maximum value. Thus, the body of the following loop will not be executed at all.

for num : 5 .. 1
   put num
end for

Other Uses of the for Loop

Generating Values Using the Loop Control Variable

The above for loop uses the default increment of one. If the desired values are not consecutive, code can be written to generate them if the difference between them is calculable. The next fragment calculates and prints even numbers using related Natural numbers in the counter.

% Print the first five even Natural numbers
for i : 1 .. 5
   num := i * 2
   put num
end for

This task could also be performed by specifying an increment other than the default value of one (1).

% Print the first five even Natural numbers
for i : 2 .. 10 by 2
   put i
end for

On the other hand, if you want to print decimal values, you must calculate them because the loop control variable must be an integer. For example, the following code will print values from 1 to 5, counting by halves.

% Print the first five even Natural numbers
for i : 2 .. 10
   num := i / 2
   put num
end for

Generating Another Ordinal Type from the Loop Control Variable

The for loop can use only integers as the values of the "loop control variable". Since the letters of the alphabet occur in order in ASCII code, it is possible to have a variable contain one after another as shown in the code below. Executing this loop will result in ABCDEFGHIJKLM being printed on a single line.

for lettervalue : ord("A") .. ord("M")
   put chr(lettervalue)..
end for

The function ord returns the ASCII value of a character, while the function chr returns the character which has a specific ASCII value.

Decrementing the Loop Control Variable

It is also possible to use a negative increment (i.e., decrement) using the reserved word DOWNTO.

% Print the first five odd Natural numbers backwards
for decreasing num : 9 .. 1 by 2
   put num
end for

© 1997-2004 DFStermole
Last Modified: 3 Mar 04