Using Conditional Clauses with the Iterative DO Statement

Previous examples showed that the DO WHILE and DO UNTIL statements enable you to execute statements conditionally and that the iterative DO statement enables you to execute statements a set number of times, unconditionally.
DO WHILE(expression); 
DO UNTIL(expression); 
DO index-variable=start TO stop BY increment;
In this DATA step, the DO UNTIL statement determines how many years it takes (13) for an investment to reach $50,000.
data work.invest; 
   do until(Capital>=50000);  
      Year+1; 
      capital+2000; 
      capital+capital*.10; 
   end; 
run;
Figure 15.5 SAS Data Set Work.Invest: Number of Years for an Investment to Reach $50,000
SAS Data Set Work.Invest
Suppose you also want to limit the number of years you invest your capital to 10 years. You can add the UNTIL or WHILE expression to an iterative DO statement to further control the number of iterations. This iterative DO statement enables you to execute the DO loop until Capital is greater than or equal to 50000 or until the DO loop executes 10 times, whichever occurs first.
data work.invest; 
   do year=1 to 10 until(Capital>=50000);  
      capital+2000; 
      capital+capital*.10; 
   end; 
run;
Figure 15.6 SAS Data Set Work.Invest: Executing DO Loop until Capital >=$50,000
SAS Data Set Work.Invest
In this case, the DO loop stops executing after 10 iterations, and the value of Capital never reaches 50000. If you increase the amount added to Capital each year to 4000, the DO loop stops executing after the eighth iteration when the value of Capital exceeds 50000.
data work.invest; 
   do year=1 to 10 until(Capital>=50000);  
      capital+4000; 
      capital+capital*.10; 
   end; 
run;
Figure 15.7 SAS Data Set Work.Invest: Increase Amount Added to Capital Using a DO Loop
SAS Data Set Work.Invest
The UNTIL and WHILE expressions in an iterative DO statement function similarly to the DO UNTIL and DO WHILE statements. As shown in the following syntax, both statements require a valid SAS expression that is enclosed in parentheses.
DO index-variable=start TO stop BY increment UNTIL(expression);
DO index-variable=start TO stop BY increment WHILE(expression);
The UNTIL expression is evaluated at the bottom of the DO loop. Therefore, the DO loop always executes at least once. The WHILE expression is evaluated before the execution of the DO loop. As a result, if the condition is initially false, the DO loop never executes.
Last updated: January 10, 2018
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.30.19