Looping with the  FOR  Keyword

Navigation:  Appendices > Macro Language > Instructions > Looping Instructions >

Looping with the  FOR  Keyword

Previous pageReturn to chapter overviewNext page

The for-to-step set of keywords 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. To interrupt the flow of a for loop, use the break or continue commands.Below is an example of the syntax :

 

for nDate = nToday to nJanOneNextYear step 7

 // do something every week for the rest of the year

endfor

 

The while loop can always be used to replace a FOR loop. 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 a WHILE loop :

 

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


Topic 105145 updated on 01-Nov-2016.
Topic URL: http://www.qppstudio.net/webhelp/index.html?loopingwiththeforkeyword.htm