Please enable JavaScript to view this site.

 

Navigation: Macros > Macro Language > Instructions > Looping

Looping with the  FOR  Keyword

Scroll Prev Up Next More

The for-to-step looping instruction are used to repeat a block of instructions while a counter is incremented by the value of the step every time.

 

The for loop is used when you want to iterate through some values and you know, before entering the loop, what the range will be. If the concept of a value increasing over a range does not seem suited to your problem, try the while loop.

 

Before the block to be repeated, place a for-to-step statement. This statement is made up of one integer variable used as loop counter, and 3 integer expressions as follows.

for nCounter = nStartVal to nEndVal step nStepVal

The first time this statement is reached, the value of nCounter is set to nStartVal. The following block of code is then performed as long as the value of nCounter is not greater than nEndVal, as would be the case in the example below :

 for nX = 3 to 2 step 1 // this will go nowhere !

The block of instructions that follows finishes when it reaches endfor. At that point the value of nCounter is increased by nStepVal and compared to nEndVal. If nCounter is still smaller than nEndVal then the block of code is performed once more.

 

If you try to change any the values used in the 3 expressions of the for statement, within the loop, the compiler will generate an error message.

 

A for loop can always be replaced by a while loop.

for nDate = nToday to nJanOneNextYear step 7
   // do something every week for the rest of the year
endfor

However, the use of a for loop, when appropriate makes code much more legible, as we can see if we consider the replacement of the above for loop by the while loop below.

nDate = nToday
if nToday <= nJanOneNextYear
   while nToday <= nJanOneNextYear
      // do something every week for the rest of the year
      …
      // finally increase the counter
      nDate = nDate + 7
   endwhile
endif

To interrupt the flow of a for loop, use the break or continue commands.

 

See also: while loops.

 


Topic 105145, last updated on 18-Apr-2020