Freigeben über


For Loops

Applies To: Microsoft Dynamics AX 2012 R3, Microsoft Dynamics AX 2012 R2, Microsoft Dynamics AX 2012 Feature Pack, Microsoft Dynamics AX 2012

The for loop is very similar to the while loop, but has the following additions:

  • The initial value to a control variable can be assigned.

  • There is a statement for incrementing or decrementing the variable.

These additions make it especially useful for traversing lists, containers, and arrays because they have a fixed number of elements. You can also apply a statement to each element and increment your way through the elements, setting the condition to test for the last element.

Syntax

The body of the for loop may be executed zero or more times according to the results of the condition test. Placeholders are enclosed in parentheses.

    for ( Initialization ; Test ; Increment ) 
    {
        Statement 
    }

Example

Print all items in a fixed array called ra with 100 reals.

    int i; // Control variable.
    ;
    for (i=1; i<=100; i+=1)
    {
        print ra[i];
    }

Comparison to while Loop

The previous example can also be written using a while loop.

    int i; // Control variable.
    ;
    i = 1;
    while (i <= 100)
    {
        print ra[i];
        i++;
    }

In general, there is a direct correspondence between for and while loops as shown in the following table.

for loop

while loop

for (Init; Test; Incr)

{

{

Init;

Body

while (Test)

}

{

Body;

Incr;

}

}

The two constructions shown in the previous table are exactly the same unless the Body contains a continue statement. In a for loop, continue moves in front of the increment. In a while loop, continue jumps to after the increment.

See also

Loops

Conditional Statements

Announcements: New book: "Inside Microsoft Dynamics AX 2012 R3" now available. Get your copy at the MS Press Store.