SAS OnlineTutor HomeFAQ PageSuggested Learning PathsContents+Searchback||next

Generating Data with DO Loops
Nesting DO Loops


Iterative DO statements can be executed within a DO loop. Putting a DO loop within a DO loop is called nesting.
     do i=1 to 20;
        more executable statements
        do j=1 to 10;
           more executable statements
        end;
        more executable statements
     end;

The DATA step below computes the value of a one-year investment earning 7.5% annual interest, compounded monthly.

     data work.earn;
        Capital=2000;
        do month=1 to 12;
           Interest=capital*(.075/12);
           capital+interest;
        end;
     run;

Let's assume the same amount of capital is to be added to the investment each year for 20 years. The new program must perform the calculation for each month during each of the 20 years. To do this, you can include the monthly calculations within another DO loop that executes twenty times.

     data work.earn;
        do year=1 to 20; 
           Capital+2000;             
           do month=1 to 12;         
              Interest=capital*(.075/12); 
              capital+interest;      
           end;                      
        end;             
     run;

During each iteration of the outside DO loop, an additional 2,000 is added to capital, and the nested DO loop executes twelve times.

     data work.earn;
        do year=1 to 20;
           Capital+2000;
           do month=1 to 12; 
              Interest=capital*(.075/12); 
              capital+interest;      
           end;              
        end;
     run;

Remember, for nested DO loops to execute correctly, you must

  • assign unique index variable names to each iterative DO statement.
     data work.earn;
        do year=1 to 20;
           Capital+2000;
           do month=1 to 12;
              Interest=capital*(.075/12);
              capital+interest;
           end;
        end;
     run;
  • end each DO loop with an END statement.
     data work.earn;
        do year=1 to 20;
           Capital+2000;
           do month=1 to 12;
              Interest=capital*(.075/12);
              capital+interest;
           end;
        end;
     run;

It is easier to manage nested DO loops if you indent the statements in each DO loop as shown above.


back||next


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

Terms of Use & Legal Information | Privacy Statement