DATA Step, Macro, Functions and more

TestPrep Question on Do Loops

Reply
Frequent Contributor
Posts: 130

TestPrep Question on Do Loops

Hi,

 

I am working through testprep ques for the base exam. I will always go through all of them to see if I understand the answer. In the cases that I don't, I will ask for help on here.

 

So far, pasted below, is the code from the first question I don't understand the answer to.

Question 5
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, wha
t are the values of the variab
les 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 
correct_answer = "D"

I would have thought that when Index reached 5, and X was 5, that, even though the do loop is still active, that the index would not be allowed to go above 5. It appears that it can go beyond the limits set in the By statement in such a case. Is that correct? I would have chosen answer B. Thanks.

 

 

Frequent Contributor
Posts: 130

Re: TestPrep Question on Do Loops

Posted in reply to ManitobaMoose

I meant to say, not "set in the By statement" but rather beyond the limits set in the Index = statement.

Super User
Posts: 6,785

Re: TestPrep Question on Do Loops

Posted in reply to ManitobaMoose

In that DO loop, the question is how does INDEX go from 1 to 5.  The process is:

 

  • Go through the loop with INDEX equal to 1.
  • At the END statement, add 2 to the value of INDEX.
  • See if the loop is now over.  (This would happen if INDEX exceeds the upper limit of 5.)
  • If the loop should continue, execute again.

So as you might expect, the loop executes 3 times with INDEX being 1, 3, and 5.  (You can see those values captured in the variable  X.)

 

At the END statement, the third time through the loop, the same process is applied.  Add 2 to the value of INDEX, giving it a value of 7.  SAS now notices that 7 is greater than the upper limit of the loop (1 to 5), so the loop ends.

 

You can see this at work by adding this statement twice:

 

put x= index=;

 

Add it once before the END statement, and again after the END statement.

The final value of INDEX always exceeds the upper limit in the DO statement.

Ask a Question
Discussion stats
  • 2 replies
  • 79 views
  • 2 likes
  • 2 in conversation