SAS OnlineTutor HomeFAQ PageSuggested Learning PathsContents+Searchback||next

Generating Data with DO Loops
Conditionally Executing DO Loops


The iterative DO statement requires that you specify the number of iterations for the DO loop. However, there are times when you want to execute a DO loop until a condition is reached or while a condition exists, but you don't know how many iterations are needed.

Suppose you want to calculate the number of years required for an investment to reach $50,000. In the DATA step below, using an iterative DO statement is inappropriate because you are trying to determine the number of iterations required for Capital to reach $50,000.

     data work.invest;
        do year=1 to ? ;
           Capital+2000;
           capital+capital*.10;
        end;
     run;

The DO WHILE and DO UNTIL statements enable you to execute DO loops based on whether a condition is true or false.


Using the DO UNTIL Statement

The DO UNTIL statement executes a DO loop until a condition is true.


General form, DO UNTIL statement:
DO UNTIL(expression);
more SAS statements
END;

where expression is a valid SAS expression enclosed in parentheses.


The expression is not evaluated until the bottom of the loop, so a DO UNTIL loop always executes at least once. When the expression is evaluated as true, the DO loop is not executed again.

Assume you want to know how many years it will take to earn $50,000 if you deposit $2,000 each year into an account that earns 10% interest. The DATA step below uses a DO UNTIL statement to perform the calculation until the value is reached. Each iteration of the DO loop represents one year of earning.

     data work.invest;
        do until(capital>=50000);
           Capital+2000;
           capital+capital*.10;
           Year+1;
        end;
     run;

During each iteration of the DO loop,

  • 2000 is added to the value of Capital to reflect the annual deposit of $2,000
  • the value of Capital is calculated
  • the value of Year is incremented by 1.

Because there is no index variable in the DO UNTIL statement, the variable Year is created in a sum statement to count the number of iterations of the DO loop. This program produces a data set with the single observation shown below. To accumulate more than $50,000 in capital, it takes thirteen years (and thirteen iterations of the DO loop).


SAS Data Set Work.Invest
Capital Year
53949.97 13



back||next


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

Terms of Use & Legal Information | Privacy Statement