DATA Step, Macro, Functions and more

Do loop

Accepted Solution Solved
Reply
Contributor
Posts: 31
Accepted Solution

Do loop

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?


Accepted Solutions
Solution
‎09-11-2017 11:18 AM
Super User
Posts: 6,939

Re: Do loop

Yes.  At the end of the third iteration, once X=7, SAS notices that 7 > 5 so the loop must be complete.

View solution in original post


All Replies
Super User
Posts: 6,939

Re: Do loop

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.

Contributor
Posts: 31

Re: Do loop

Posted in reply to Astounding

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!!

Solution
‎09-11-2017 11:18 AM
Super User
Posts: 6,939

Re: Do loop

Yes.  At the end of the third iteration, once X=7, SAS notices that 7 > 5 so the loop must be complete.

Valued Guide
Posts: 596

Re: Do loop

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

Super User
Posts: 13,950

Re: Do loop

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.

 

☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 5 replies
  • 378 views
  • 3 likes
  • 4 in conversation