Finishing the loop

Before we are going to test our repeating logic, there are two more things that need to be added:

  • an end condition;
  • something to repeat.

Setting an end condition

First, we have to set an end condition, to make sure the repeating stops eventually! This can be done by double-clicking on the repeat iconrepeat item in the Actions panel and selecting the icon with the three dots: here you can set the condition.

Let us say we have asked how many employees there are in main.employees.number, and we want to repeat the graph as many times as there are employees.

In order to do this, make sure that you have selected the counter variable as first, and the question that asks how many employees there are as second variable. The comparison operator should be set to >= (greater or equal to). Detailed information about how conditions work can be found here.

setting the repeat's end condition
setting the repeat’s end condition

Explanatory note: We use the greater-than-or-equals operator >= because the counter starts at 0 (zero), and the condition is checked at the beginning of each loop. Had we used the greater-than operator >, we would be calling the graph one time too many.

Adding something to be repeated

A common use case for looping or repeating is calling a (sub)graph multiple times in a row, so let us add a graph here.

In order to do this, you have to select Graph > Call graph from the menu (see model structure for information on calling graphs).

The last thing you will have to do is to ensure that the call graph item is placed between the repeat and until items in the actions list. This will make sure that the (sub)graph is repeated. You can do this by selecting the item you want to move up or down in the actions list and clicking on one of the arrows on the side.

order of action items when repeating a graph
order of action items when repeating a graph

NOTE The graph will add new iterations automatically, but there may be times you want to be explicit about exactly which iteration number you want to use. In that case you will have to check Use iteration, after which a textbox will appear where you’ll have to give the iteration a name. Call it ‘counter’. You have to make sure that this is the same counter we used when adding the repeating logic, so if you gave the iteration a different name make sure you give this one the same!

Using a counter to repeat the subgraph with an explicit iteration
Using a counter to repeat the subgraph with an explicit iteration

When you run the model, and say that you have two employees working for you, the application will go on to present the page to fill in the employee’s information two times. After that, it will continue to the rest of the model.

Now that you get the basic idea of how to repeat actions, the next part will go into more detail about things you may encounter when repeating actions or graphs.