Contents Previous Next Subchapters

For Statement
Syntax for variable = start to finish block
See Also block , while , goto

Description
Executes block the specified number of times where start and finish are integer scalars.

The variable is initialized with the value start and is incremented by one each time the block is executed. It has the value finish the last time the block is executed.

Tutorial
If you enter
     for i = 1 to 3 begin
          print i
     end
O-Matrix will respond
     1
     2
     3
A variable defined before the for statement can be used to accumulate a result. For example, to calculate 5!, which is 5 x 4 x 3 x 2 x 1, enter
     fact = 1
     for i = 1 to 5 begin
          fact = fact * i
     end
     print fact
which will result in
     120
You can nest a for statement within another loop. For example,
     for i = 1 to 2 begin
          for j = 2 to 5 begin
               print "i =", i, " j =", j
          end
     end
will result in
     i = 1  j = 2
     i = 1  j = 3
     i = 1  j = 4
     i = 1  j = 5
     i = 2  j = 2
     i = 2  j = 3
     i = 2  j = 4
     i = 2  j = 5

Reference
The limits of the for loop are evaluated only before the first execution of the block. If you enter
     n = 3
     for i = 1 to n begin
          n = 2
          print i
     end
O-Matrix will respond
     1
     2
     3