BookmarkSubscribeRSS Feed
he2185
Calcite | Level 5

I am reviewing for the Base SAS certification and was questioning one of the answers in the book.  The question is:

 

In the following program, complete the statement so that the program stops generating observations when Distance reaches 250 miles or when 10 gallons of fuel have been used.

 

 

data work.go250; 
  set cert.cars; 
  do gallons=1 to 10 ... ; 
    Distance=gallons*mpg; 
    output; 
  end; 
run;

The correct answer, according to the book, is while(Distance<=250). However, I believe the answer is until(Distance=250).

 

My understanding of the WHILE expression is that it is evaluated before the execution of the DO loop, so if Distance reaches 250, the do loop will still execute because the statement (Distance <= 250) is still true.  I made up a dataset in SAS Studio to see what would happen with both the WHILE and UNTIL statements. 

 

WHILE statement

 

 

data cars;
	input  mpg;
	datalines;
50 
	;
run;

data work.go250; 
  set cars; 
  do gallons=1 to 10 while(Distance le 250); 
    Distance=gallons*mpg; 
    output; 
  end; 
run;
proc print data = go250; run;

 

Obs	mpg	gallons	Distance
1	50	1	50
2	50	2	100
3	50	3	150
4	50	4	200
5	50	5	250
6	50	6	300

 

 

 

UNTIL statement

 

data work.go250_2; 
  set cars; 
  do gallons=1 to 10 until(Distance=250); 
    Distance=gallons*mpg; 
    output; 
  end; 
run;

proc print data = go250_2; run;
Obs	mpg	gallons	Distance
1	50	1	50
2	50	2	100
3	50	3	150
4	50	4	200
5	50	5	250

Based on the output, it looks like the UNTIL statement satisfies the requirement of "...Distance reaches 250 miles..."

 

Any insights would be appreciated. Thanks!

 

2 REPLIES 2
Astounding
PROC Star

First, the WHILE condition would be correct, but needs to remove the equal sign:

 

while (distance < 250)

 

Second, UNTIL would be incorrect because UNTIL always executes the first time.  It doesn't check the truth or falsity of the condition at the top of the loop, but only checks it at the END statement.  So if your original DISTANCE was 300, UNTIL would still execute (improperly) once.

ballardw
Super User

Did the possibly answers include any option with the LEAVE statement?

That would be another option.

 

data example;
   mpg = 28.2;
   do gallons=1 to 10;
      distance= gallons * mpg;
      if distance > 250 then leave;
      output;
   end;
run;

whether the LEAVE comes before or after the output would depend on the actual intent of the rule.

 

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 2 replies
  • 851 views
  • 0 likes
  • 3 in conversation