Skip to content
AgileLogics
6 min read

DO Loops

Prerequisites: Conditional logic

The DATA step already loops over rows. DO loops repeat work within one row — or create many rows from nothing.

Iterative DO

data savings;
   balance = 1000;
   do year = 1 to 5;
      balance = balance * 1.10;
      output;
   end;
   format balance dollar10.2;
run;

proc print data=savings noobs;
run;
   balance    year

 $1,100.00      1
 $1,210.00      2
 $1,331.00      3
 $1,464.10      4
 $1,610.51      5
  • OUTPUT inside the loop writes one row per year. Without it, you'd get a single row with the final values.
  • do i = 1 to 10 by 2; changes the step; by -1 counts down.
  • After the loop ends, the index is one step past the end (here, year would be 6 without the OUTPUTs).
  • You can loop over a list of values: do color = 'red', 'green';.

DO WHILE and DO UNTIL

data _null_;
   balance = 1000;
   years = 0;
   do while (balance < 2000);
      balance = balance * 1.10;
      years + 1;
   end;
   put years= balance= 7.2;
run;
years=8 balance=2143.59
  • DO WHILE (condition) checks before each pass, so it may run zero times.
  • DO UNTIL (condition) checks after each pass, so it always runs at least once.
  • years + 1; is a sum statement — it adds 1 to years. You'll meet it properly in the BY-group lesson.

Generating data

data squares;
   do n = 1 to 5;
      square = n ** 2;
      output;
   end;
run;

proc print data=squares noobs;
run;
n    square

1       1
2       4
3       9
4      16
5      25

This is how you build test data, calendars, or simulation inputs without a file.

Common mistakes

  • An infinite DO WHILE whose condition never becomes false — SAS Studio keeps running until you cancel. Make sure the loop changes the variable it tests.
  • Forgetting that a DO loop runs inside each DATA step iteration: with set big; plus do i = 1 to 1000;, the loop runs 1,000 times per row.

Practice

Create a data set of the multiplication table for 7, from 7 × 1 to 7 × 10, with variables n and result.

Show solution
data seven;
   do n = 1 to 10;
      result = 7 * n;
      output;
   end;
run;

proc print data=seven noobs;
run;
 n    result

 1       7
 2      14
 3      21
 4      28
 5      35
 6      42
 7      49
 8      56
 9      63
10      70