xHarbour Reference Documentation > Statement Reference xHarbour Developers Network  

FOR

Executes a block of statements a specific number of times.

Syntax

FOR <nCounter> := <nStart> TO <nEnd> [STEP <nIncrement>]
  <Statements>
  [EXIT]
  <Statements>
  [LOOP]
NEXT

Arguments

FOR <nCounter> := <nStart>
<nCounter> is the name of the variable that holds a counter value used to control the number of iterations of the FOR...NEXT loop. If <nCounter> does not exist when the loop is entered, it is created as a PRIVATE variable. The value <nStart> is a numeric start value to initialize <nCounter> with when the FOR statement is executed for the first time.
TO <nEnd>
<nEnd> is a numeric value that controls the termination of the FOR...NEXT loop. As soon as <nCounter> is greater than or equal to <nEnd>, the statements between FOR and NEXT are no longer executed.
STEP <nIncrement>
<nIncrement> is a numeric value <nCounter> is incremented with for each iteration of the loop. If not specified, it defaults to 1. When <nIncrement> is a negative value, the loop ends when <nCounter> is smaller than or equal to <nEnd>.
EXIT
The EXIT statement unconditionally terminates a FOR...NEXT loop. Program flow branches to the first statement following the NEXT statement.
LOOP
The LOOP statement branches control unconditionally to the FOR statement, i.e. to the begin of the loop.

Description

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.

Info

See also:AEval(), FOR EACH, DO CASE, DO WHILE, IF, SWITCH, WITH OBJECT
Category: Control structures , Statements

Example

// 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

Copyright © 2006-2007 xHarbour.com Inc. All rights reserved.
http://www.xHarbour.com
Created by docmaker.exe