Iterative DO Loops


You can use iterative DO loops to repetitively execute statements based on the value of an index variable.


General form, iterative DO loop:
DO index-variable specification;
      more SAS statements;
END;

where

  • index-variable names a variable whose value governs the execution of the DO loop.

  • specification can be a
    • discrete value such as 1, 45, 10342
    • range of values such as 1 to 5 or 10 to 100 by 10.

  • more SAS statements are statements executed within the loop. The END statement closes the DO loop and returns control to the DO statement.

NOTE: When a discrete value is specified for the index-variable, the loop executes only once for that value.


In the following example, the index-variable COUNT is assigned an initial value of 1. The expression COUNT=1 is evaluated before the statements in the loop are executed. The END statement passes control back to the DO statement where the value of COUNT is then set to 16. The expression COUNT=16 is evaluated, and the loop executes once more. Now there are no more values for COUNT, so the loop stops.

     do count=1,16;
cost=salary+equip;
end;

If the specification is a range of values, the loop executes from the initial value to the ending value. For example, the following statement executes the loop when the value of COUNT is 1, 2, 3, and 4. When the value of COUNT exceeds 4, the loop does not execute.

     do count=1 to 4;
cost=salary+equip;
end;

The default increment is 1; however, you can specify another increment. Here the value of COUNT is incremented by 2, so the loop executes only when the value of COUNT is 2, 4, 6, and 8.

     do count=2 to 8 by 2;
cost=salary+equip;
end;





Copyright © 2002 SAS Institute Inc., Cary, NC, USA. All rights reserved.

Terms of Use & Legal Information | Privacy Statement