How to use a DO UNTIL Statement in SAS

A DO UNTIL statement in SAS is a looping statement that performs a set of instructions until a certain condition is met. It includes a DO statement, which contains the instructions to be performed, and a UNTIL statement, which contains a logical expression that must evaluate to true before the loop is terminated. A DO UNTIL statement is particularly useful when you are not sure how many times a loop needs to be executed. It allows you to perform a set of instructions until a certain condition is met without having to know the exact number of times the loop needs to be repeated.


You can use a DO UNTIL statement in SAS to do some loop over and over until some condition has been met.

The following examples show two different ways to use this statement in practice.

Example 1: DO UNTIL Statement in SAS

The following code shows how to use a DO UNTIL statement in SAS to create a dataset that contains two variables called var1 and var2 that continue to generate new values until the value of var1 is greater than 100:

/*create dataset using DO UNTIL statement*/
data my_data;

var1 = 1;
var2 = 1;

do until(var1 > 100);
    var1 = var1 + var2; 
    var2 = var1 * var2;
    var1 + 1;
    
output;

end;

run;

/*view dataset*/
proc print data=my_data;

The DO UNTIL statement continued to generate new values for var1 and var2 until the value of var1 was greater than 100.

Once the value of var1 exceeded 100, the DO UNTIL statement stopped and new values stopped being added to the dataset.

Example 2: DO UNTIL Statement with TO Statement in SAS

The following code shows how to use a DO UNTIL statement with a TO statement in SAS to create a dataset that contains two variables called var1 and var2 that continue to generate new values until the value of var1 is greater than 10:

/*create dataset using DO UNTIL statement with TO statement*/
data my_data;

var1 = 0; 

do var2 = 1 to 5 until(var1 > 10);   
    var1 = var2**2;
    
output;

end;

run;

/*view dataset*/
proc print data=my_data;

The TO statement told SAS to attempt to generate values for var2 ranging from 1 to 5 but only until the value of var1 was greater than 10.

Once the value of var1 exceeded 10, the DO UNTIL statement stopped and new values stopped getting added to the dataset.

The following tutorials explain how to perform other common tasks in SAS:

x