FOR ... ENDFOR Command
Executes a set of commands a specified number of times.
FOR Var = nInitialValue TO nFinalValue [STEP nIncrement] Commands [EXIT] [LOOP] ENDFOR | NEXT
- Specifies a variable or an array element that acts as the counter. The variable or array element doesn't have to exist before FOR ... ENDFOR is executed.
- nInitialValue TO nFinalValue
- nInitialValue is the initial value of the counter; nFinalValue is the final value of the counter.
- STEP nIncrement
- nIncrement is the amount the counter is incremented or decremented. If nIncrement is negative, the counter is decremented. If you omit STEP, the counter is incremented by 1.
- Specifies the Visual FoxPro commands to be executed. Commands can include any number of commands.
- Transfers control from within the FOR ... ENDFOR loop to the command immediately following ENDFOR. You can place EXIT anywhere between FOR and ENDFOR.
- Returns control directly back to the FOR clause without executing the statements between LOOP and ENDFOR. The counter is incremented or decremented as if ENDFOR were reached. LOOP can be placed anywhere between FOR and ENDFOR.
A variable or an array element is used as a counter to specify how many times the Visual FoxPro commands inside the FOR ... ENDFOR loop are executed.
The Visual FoxPro commands after FOR are executed until ENDFOR or NEXT is reached. The counter MemVarName is then incremented by the value of nIncrement. If you omit the STEP clause, the counter is incremented by 1. The counter is then compared with nFinalValue. If the counter is less than or equal to nFinalValue, the commands following the FOR clause are executed again. If the counter is greater than nFinalValue, the FOR ... ENDFOR loop is exited and program execution continues with the first command following ENDFOR or NEXT.
Note The values of nInitialValue, nFinalValue, and nIncrement are only read initially. However, changing the value of the counter MemVarName inside the loop affects the number of times the loop is executed.
If the value of nIncrement is negative and the initial value nInitialValue is greater than the final value nFinalValue, the counter is decremented each time through the loop.
In Example 1, the numbers 1 through 10 are displayed.
Example 2 uses memory variables for the initial, final, and STEP values to display all even-numbered records from 2 through 10 in
* Example 1 CLEAR FOR gnCount = 1 TO 10 ? gnCount ENDFOR * Example 2 SET TALK OFF CLOSE DATABASES OPEN DATABASE (HOME(2) + 'Data\testdata') USE customer && Opens Customer table STORE 2 TO gnI && Initial value STORE 10 TO gnJ && Final value STORE 2 TO K && Step value FOR gnCount = gnI TO gnJ STEP K GOTO gnCount && Move record pointer DISPLAY company && Display company name ENDFOR