7.2 For loops

For loops may be used to execute a series of commands multiple times. Pyxplot allows for loops to follow either the syntax of the BASIC programming language, or the C syntax:

for <variable> = <start> to <end> [step <step>]
                          [loopname <loopname>]

for (<initialise>; <criterion>; <step>)

Here, <code> may be substituted by any block of Pyxplot commands enclosed in braces {}. The closing brace must be on a new line after the last command of the block.

The first form is similar to how the for command works in BASIC. The first time that the script block is executed, variable has the value start. Upon each iteration of the loop, it is incremented by amount step. The loop finishes when the value exceeds end. If step is negative, then end is required to be less than or equal to start. A step size of zero is considered to be an error. The iterator variable can have any physical dimensions, so long as start, end and step all have the same dimensions, but the iterator variable must always be a real number. If no step size is given then a step size of unity is assumed. As an example, the following script would print the numbers 0, 2, 4, 6 and 8:

for x = 0 to 10 step 2
  print x

In the C form of the for command, three expressions are provided, separated by semicolons. These are evaluated (a) when the loop initialises, (b) as a boolean test of whether the loop should continue iterating, and (c) at the end of each iteration, usually to increment/decrement variables as required. For example:

for (i=1,j=1; i<=256; i*=2,j++) { print "%3d %3d"%(j,i); }

The syntax

for (a; b; c) { ... ; }

is almost equivalent to

a; while (b) { ... ; c ; }

with the single exception that continue statements behave slightly differently. In the C form of the for command, the continue statement executes the expression c before the next iteration is started, even though the while loop above would not.

The optional loopname which can be specified in the for statement is used in conjunction with the break and continue statements which will be introduced in Section 7.6.