Obsidian | Level 7

## 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?

1 ACCEPTED SOLUTION

Accepted Solutions
PROC Star

## 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.

5 REPLIES 5
PROC Star

## 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.

Obsidian | Level 7

## Re: Do loop

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

PROC Star

## 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.

Ammonite | Level 13

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

## 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.

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