The following SAS program is submitted: data WORK.LOOP;
X = 0;
do Index = 1 to 5 by 2;
X = Index; end; run;
Upon completion of execution, what are the values of the variables X and Index in the SAS data set named WORK.LOOP?
A. X = 3, Index = 5
B. X = 5, Index = 5
C. X = 5, Index = 6
D. X = 5, Index = 7
Why the correct_answer = "D"?? I thought index should never exceed 5?
Yes. At the end of the third iteration, once X=7, SAS notices that 7 > 5 so the loop must be complete.
Just the opposite ... the final value of INDEX will always exceed 5.
The key issue is how INDEX gets incremented. Each time the loop reaches the END statement, it adds 2 to the value of INDEX. Then it considers, "Am I done yet?" The criterion that it uses to determine whether the loop is done: does INDEX now exceed the upper bound of 5.
Oh so it means if X=1, index=3, X=3, index=5, X=5,index=7? Sorry just started learning SAS, pardon if I am weak at my foundation, thanks!!
Yes. At the end of the third iteration, once X=7, SAS notices that 7 > 5 so the loop must be complete.
This looks a lot like homework 😉 but still....
In this form of the Do statement execution of the step continues until the value of the index exceeds the stop value - you can find more here http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a000201276.htm
1) Incomplete data step
Iterated do loops: ie. Do var = 1 to value (by otherval)
always interate until the value limit is exceeded. At which point the the code inside the loop is not executed.
It is similar to Do while (x < 10);
x+1;
end;
the condition is true until x is greater than or equal to 10. At which time x is larger than the loop limit, the loop doesn't execute but the value of x is retained.
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.