FOR-EACH (For Each)

Free-Form Syntax FOR-EACH{(H)} item IN array | %LIST | %SPLIT | %SUBARR
Code Factor 1 Extended Factor 2
FOR-EACH   item IN array | %LIST | %SPLIT | %SUBARR

The FOR-EACH operation begins a group of operations to process the items in the array, sub-array, or %LIST one at a time.

The first operand of FOR-EACH is a variable. It cannot be an array.

The second operand of FOR-EACH can be an array, %LIST, %SPLIT, or %SUBARR. It must have a data type that is compatible with the first operand. If the first operand of FOR-EACH is a data structure, the second operand must be related to the first operand by LIKEDS keywords.

Each element of the second operand is iteratively assigned to the first operand. Within the group of operations between the FOR-EACH operation and the ENDFOR operation, the first operand holds the value of the element to be processed.

For numeric values, the half-adjust operation code extender 'H' is allowed. The rules for half adjusting are equivalent to those for the arithmetic operations. Ensuring Accuracy

Examples

In the following example, each element of the order_states array is assigned to the state variable.

DCL-S order_states CHAR(10) DIM(3);
DCL-S state CHAR(20);

order_states(1) = 'Open';
order_states(2) = 'Active';
order_states(3) = 'Closed';
FOR-EACH state in order_states;
   DSPLY state;
ENDFOR;
The program displays the following output:

DSPLY  Open
DSPLY  Active
DSPLY  Closed

In the following example, the two FOR-EACH statements are the same except the second FOR-EACH operation has the operation extender 'H', indicating that half adjusting is performed.

When prices(1), with value 5.279, is assigned to price, the value of price, which has only two decimal positions, is 5.27 for the first FOR-EACH loop and 5.28 for the second FOR-EACH loop with half adjusting.


DCL-S prices PACKED(15:5) DIM(2);
DCL-S price PACKED(15:2);

prices(1) = 5.279;
prices(2) = 5.271;

FOR-EACH price in prices;
   DSPLY (%char(price));
ENDFOR;

FOR-EACH(H) price in prices;
   DSPLY (%char(price));
ENDFOR;
The program displays the following output:

DSPLY  5.27
DSPLY  5.27
DSPLY  5.28
DSPLY  5.27

See Examples of %LIST for an example of FOR-EACH processing each item in a list specified with built-in function %LIST.

See Examples of %SPLIT for an example of FOR-EACH processing each item in a temporary array returned by built-in function %SPLIT.