S T R U C T O R I Z E R - User Guide
Elements > FOR loop

Loop styles

An element of type FOR loop is used to repeat certain instructions a pre-determined number of times. Structorizer supports two varieties of FOR loops:

  1. COUNTING loop — the traditional style. The loop increments (or decrements) a number between an initial and a final limit of an interval. It is said to count the executed passes through the loop. Consequently, you have to specify a counter variable as well as its initial and final value. By default the counter variable is automatically incremented by one after each execution of the loop body.
    You may specify a different increment (step value), which might be negative but it must be a non-zero integer constant if you want your loop to be executable or sensibly exported to a programming language of your choice. All these parameters form the control phrase, separated by configurable keywords.
    Examples for counting FOR loop headers:
        for i <- 1 to 15
        pour j <- 10 à -10, pas = -2
  2. TRAVERSING loop — the loop body is repeated for every single element of a given collection. The elements are not required to be numbers, they may be of any data type. Therefore you will have to specify a variable representing the current element, and of course a collection, which will have to be an array, obviously. (See Executor for details how array variables and array expressions are used in Structorizer.)
    Examples for traversing FOR loop headers (more examples further below):
        foreach elem in {"good", "better", "best"}
        para numero en numeros                (where numeros should be an array variable)

The underlined keywords (or key string sequences) disambiguating and separating the parameters of the loop are configurable in the Parser Preferences.

This is how you may add a FOR loop to your diagram:

1. Select an element in your diagram after (or before) which you want to insert the FOR loop:

FOR loop insertion

2. Now either select the FOR loop symbol in the toolbar (see red box in the image above — note that the FOR loop symbol, and likewise its appearence in the diagram, may look different, depending on whether or not the DIN representation is chosen) or open the context menu, choose the "Add" submenu, then either "Before" or "After", and eventually select the respective FOR loop entry. Alternatively, you may press the <F7> or <Shift><F7> key (see Keybindings).

3. When the editor pops up, you will see the following form. The screenshot shows it prepared for specifying a counting loop (upper radio button selected). The labels and default field contents are influenced by both Parser Preferences and Structure Preferences (we will discuss his later). Now you have several ways to set up your loop.

FOR loop editor

a) Fill in the text fields in the form region marked by the green box in the screenshot below. For a counting loop give the counter variable a name, specify its initial (start) value and its final (end) value. In addition, you might specify a different increment constant (negative in order to decrement). Since version 3.32-11 you get autocompletion proposals for known variable names etc. The editor will instantly compose the resulting control phrase from your input and display it in the (disabled) text area beneath. The step specification in the control phrase will be omitted while the "Increment" field contains the default constant 1:

FOR loop editing via the separate text fields

b) If you select the lower one of the two radio buttons (labelled "foreach" here), you will be presented the form for a traversing loop instead (see screenshot below). Again, you will have to specify the name of the loop variable but then a list of values, preferably comma-separated and within curly braces. But it might also be the name of an array variable or just a space-separated enumeration of some values. The listed values are not required to be numbers, not even literals. As before, the editor will immediately compose and present the control phrase.

FOR loop editor in traversing form mode

c) By selecting the "Full Text Editing" checkbox, however, the editor-internal synchronisation changes direction, i.e. now the text area (marked by a green box in the image below) will be enabled whereas the radio buttons and the form fields in the upper region simply show the conclusions Structorizer derives from parsing the control phrase you are writing. The parsing success depends on the keywords configured in Parser Preferences for counting (FOR) and traversing (FOR-IN) loops. The structured text fields in the upper region will immediately be synchronised whenever you touch the text. Be aware that the form fields may show some strange things while your control phrase is incomplete, incongruent, or ambiguous.

FOR loop editing via the compound text area

d) As soon as the entered text rather resembles the control phrase of a traversing loop (i.e. a FOR-IN loop), the radio buttons will switch and the upper part of the editor will change its appearance, i.e. the set of form fields including the labels will alter as the next screenshot demonstrates.

FOR-IN loop editing via the compound text area

Synchronisation between the upper text fields and the larger text area starts as soon as you click into one of the active fields or toggle the "Full Text Editing" checkbox.

4. Fill in some helpful description in the comment area if you like — this will be the loop comment, obviously. Then commit the data by clicking the "OK" button or pressing key combination <Shift><Enter>.

5. Add instructions to the body of your loop. Therefore first select the empty element and then select an arbitrary type of element to insert it.

Element insertion to the FOR loop body

FOR loop with body

6. If you want to add instructions after the loop (instead of to the loop body) then first select the upper or left outer part of the loop element:

FOR loop - adding after the loop

Now, this might be the complete diagram to compute the average (or mean value) of the numbers inserted to the valueArray, the two similar FOR loops are coloured light-blue:

FOR loop usage for average computation

Note:

  1. Start and end value may be arbitrary expressions (though they should compute to integer values), whereas the step width (i.e. the increment) must always be an integer literal, otherwise it wouldn't be a predictable counting and you should use a WHILE loop instead. (Hint: you may easily transmute a FOR loop of counting type into an equivalent WHILE loop construct.)
  2. The Executor will reject any attempt to manipulate the loop variable within the loop body as illegal interference with the loop control mechanism (from version 3.25-10 on; before it just hadn't an impact on the loop control). Also see Analyser Preferences.

Download Demo.

Relation between Preferences and Editor

The image below explains where the different labels and settings come from. The keywords and strings in the green boxes (also the "foreach" label) are fed from the Parser Preferences and control the detection of the FOR loop parameters within the control phrase (loop header). So they may look different with other settings! The blue-boxed text in the full text area is the default text configured in the Structure Preferences. This will already have been filled in here when you add a new FOR loop and it decides which set of form fields is presented. If your default control phrase is that of a traversing loop then the lower radio button with its corresponding form fields will be active on opening the editor. If your default phrase cannot not be classified (because it is neither compatible with the parser preferences of a counting loop nor with those of a traversing loop) then the result is undefined and the form fields are likely to show some strange tokens.
Remark: The assignment symbol displayed between the "Counter variable" field and the "Start value" will always be "<-", but on composing the control text line from the upper text fields the assignment symbol appearing in the text area might be ":=" instead if the default FOR loop content configured in the Structure Preferences represents a counting loop using the ":=" operator. (Both "<-" or ":=" are accepted as assignment operators by Structorizer — whereas a simple "=" won't.)

FOR loop separator provenance

Error Messages and Hints

The editor has a non-editable field where it may display some message if you happen to enter e.g. a non-integral value (or an expression) for the increment in full text mode, or if it detects some syntactically defective value list in case of a traversing loop. See the screenshots below for an example.

FOR loop with inacceptable step width

FOR-IN loop with incomplete value list

If you switch the loop style between counting and traversing loop via the radio buttons then in most cases the loop parameters filled in so far won't make sense anymore and will have to be discarded. To protect you against inadvertent data loss, the editor will raise a warning dialog allowing you to back off (cancel the change):

Warning dialog on altering the loop style

On changing from a counting loop with only constant parameters, however, the editor would convert it to an equivalent traversing loop, if the number of elements doesn't exceed a reasonable limit (currently 25). The example shows such a counting loop before altering the loop style...:

Counting loop with all constant parameters

... and thereafter:

Loop converted into a equivalent traversing loop

The conversion above is not reversible, i.e. the editor won't bother to find out whether a value sequence is a continuously enumerable integer interval. Actually, in most cases such a conversion would not be possible.

If you edit an existing FOR loop then the editor will automatically detect the style of your loop and present the parameters in the form fields. If the editor opens with "Full Text Editing" mode being active, however, then some discrepancy among the stored control phrase and a phrase generically composed from the contents of the form fields was detected.

Further Examples and Syntactic Possibilities

In the diagram below you see a counting loop and several traversing loops (configured with keyword foreach here), even nested ones (green).

Demo diagram for different FOR loop types

As you may see, in addition to array variables and array initialisation lists, mere item enumerations (separated by comma or even blanks) are also accepted (yellow loops).

Obviously, a list consisting by design of a single atomic element, as in e.g.

foreach elem in 23

doesn't make much sense since no loop would be required to apply the loop body (not shown here) just once to this only value. Therefore it is syntactically not supported.

If the list consists of a single string, however, then the loop body will be executed for every character of the string (since release 3.27):

foreach c in "This string will be split"

If the collection part consists of a single variable, as in

foreach elem in some_variable

then the variable is required to be an array or string variable and will be handled this way. If there are two or more variables, in contrast, then they will be treated as elements, i.e. as if they were enclosed in braces (like in the outer one of the green loops).

Hint: You may decompose a counting FOR loop into an equivalent sequence of an initialisation instruction and a WHILE loop, simply by means of the transmutation wand Magic wand icon for transmutation.