Home > Enterprise >  Do while loop in SAS
Do while loop in SAS

Time:10-07

I am referring the SAS documentation page to understand the difference between DO while and DO until loops in SAS. While referring this document, I came to a conclusion that whenever I used DO while loop, the inequality of while statement should always less than (or less than or equal). The inequality cannot be greater than (or greater than or equal).

The reason is follows. When I ran this code:

data _null_;
n=0;
   do while(n<5);
      put n=;
      n 1;
   end;
run;

I got the output as 0,1,2,3,4.

But When I ran this code, I got nothing.

data _null_;
n=0;
   do while(n>5);
      put n=;
      n 1;
   end;
run;

Is my conclusion correct, or am I missing something?

Thank you 1:

CodePudding user response:

It is not really whether you use > or <. But the logic of what to test is reversed. With DO WHILE() you execute the loop when the condition is TRUE. With DO UNTIL() you continue executing when the condition is FALSE.

11   data _null_;
12     do while(n<5);
13       put n @;
14       n 1;
15     end;
16   run;

0 1 2 3 4
NOTE: DATA statement used (Total process time):
      real time           0.00 seconds
      cpu time            0.00 seconds


17   data _null_;
18     do until(n>=5);
19       put n @;
20       n 1;
21     end;
22   run;

0 1 2 3 4
NOTE: DATA statement used (Total process time):
      real time           0.00 seconds
      cpu time            0.00 seconds

The other big difference is when the test is made. With DO WHILE() the test is before the loop starts. With DO UNTIL() it is after the loop finishes. So with DO UNTIL() the code always executes at least once.

Note your example is more easily done using an iterative DO loop instead.

6    data _null_;
7      do n=0 to 4;
8        put n @;
9      end;
10   run;

0 1 2 3 4
  • Related