| xHarbour Reference Documentation > Statement Reference | 
![]()  | 
  ![]()  | 
  ![]()  | 
 
Executes a block of statements a specific number of times.
FOR <nCounter> := <nStart> TO <nEnd> [STEP <nIncrement>] <Statements> [EXIT] <Statements> [LOOP] NEXT
The FOR...NEXT statements form a control structure that executes a block of statements for a specific number of times. This is controlled by the <nCounter> counter variable which gets assigned the value <nStart> when the loop is entered for the first time. The loop iterates the statements between FOR and NEXT and adds the value <nIncrement> to <nCounter> each time the NEXT statement is reached or a LOOP statement is executed.
The value <nEnd> identifies the largest value for <nCounter> (<nIncrement> is positive) or its smallest value (<nIncrement> is negative) after which the FOR...NEXT loop terminates.
Note: The expressions in the FOR statement are evaluated each time a new iteration begins. As a consequence, new values can be assigned to <nCounter> or <nEnd> while the loop executes.
| See also: | AEval(), FOR EACH, DO CASE, DO WHILE, IF, SWITCH, WITH OBJECT | 
| Category: | Control structures , Statements | 
// This example shows a typical scenario for a FOR..NEXT loop
// where an array is filled with data, and stored data is output.
   PROCEDURE Main
      LOCAL aFields, i
      USE Customer
      aFields := Array( FCount() )
      // fill array in regular order
      FOR i:=1 TO FCount()
         aArray[i] := FieldName(i)
      NEXT
      USE
      // output data in reverse order
      FOR i:=Len( aArray ) TO 1 STEP -1
         ? aArray[i]
      NEXT
   RETURN
http://www.xHarbour.com