leave and continue sas

SAS Loops – Understanding Leave and Continue

  • Post author:
  • Post category:Base SAS
  • Post comments:0 Comments
  • Reading time:3 mins read

The SAS language sometimes appears ambiguous to programmers with experience in other languages because it doesn’t support statements like “break” and “continue.” 

In SAS, the LEAVE statement is equivalent to the “break” statement. It provides a way to exit an iterative loop immediately.

By using CONTINUE statements, SAS DATA skips over any remaining loop statements and starts the next iteration.

The LEAVE statement

The Leave statement stops processing the current loop and begins processing the next statement in the sequence.

data _null_;
   do i= 1 to 10;
      if i = 5 then leave;
      put i=;
   end;
 ;
 put 'Loop Over';
run;

Results:

i=1
 i=2
 i=3
 i=4
 Loop Over

In the above example, even though the loop is till 10, it will exit when i=5 because of the Leave statement.

The Continue Statement

When the CONTINUE statement is used, the DATA step skips the remaining body of the loop and moves on to the next iteration. The condition is used to skip processing when it is true.

data _null_;
   do i= 1 to 10;
      if i = 5 then continue;
      put i=;
   end;
 ;
 put 'Loop Over';
run;

Results:

i=1
 i=2
 i=3
 i=4
 i=6
 i=7
 i=8
 i=9
 i=10
 Loop Over

We have a similar example, with the only difference of adding the continue statement. The SAS statement if i = 5 then continue; means if the value of i=5, then skip and move to the next iteration. You can see that i=5 has been skipped from the output.

Leave and Continue in SAS
Leave and Continue in SAS

The CONTINUE and the LEAVE statements are “jump statements” that tell the program the location of the next statement to execute. 

Using LEAVE and CONTINUE statements, SAS loops can be managed easily. In SAS, there is no need to code additional logic, such as the value of a counter variable, to determine what to do on the last iteration.

Every week we'll send you SAS tips and in-depth tutorials

JOIN OUR COMMUNITY OF SAS Programmers!

Subhro

Subhro provides valuable and informative content on SAS, offering a comprehensive understanding of SAS concepts. We have been creating SAS tutorials since 2019, and 9to5sas has become one of the leading free SAS resources available on the internet.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.