SAS OnlineTutor HomeFAQ PageSuggested Learning PathsContents+Searchback||next

Generating Data with DO Loops
Constructing DO Loops


Counting DO Loop Iterations

In some cases, it is more useful to create a variable to count and store the number of iterations in the DO loop. Then you can drop the index variable from the data set.

     data work.earn (drop=year);
        Value=2000;
        do year=1 to 20;
           Interest=value*.075;
           value+interest;
           Years+1;
        end;
     run;
SAS Data Set Work.Earn
Value Interest Years
8495.70 592.723 20
The sum statement accumulates the number of iterations of the DO loop and stores the total in the variable Years. The final value of Years is stored in the data set.

You can also include an OUTPUT statement within the DO loop to write an observation to the data set for each iteration of the DO loop. The OUTPUT statement writes the current values to the data set immediately. By including the OUTPUT statement, you override the automatic output at the end of the DATA step. When the index variable is 21, the observation is not written to the data set.

     data work.earn;
        Value=2000;
        do year=1 to 20;
            Interest=value*.075;
            value+interest;
            output;
         end;
     run;
Partial Listing of
SAS Data Set Work.Earn
Value year Interest
2150.00 1 150.000
2311.25 2 161.250
2484.59 3 173.344
2670.94 4 186.345
2871.26 5 200.320
3086.60 6 215.344
3318.10 7 231.495
3566.96 8 248.857
... ... ...
8495.70 20 592.723


During each iteration of the DO loop, an observation is written to the Work.Earn data set.


back||next


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

Terms of Use & Legal Information | Privacy Statement