data WORK.LOOP;
X = 0;
do Index = 1 to 5 by 2;
X = Index;
end;
run;
Q) Upon completion of execution, what are the values of the variables X and Index in the SAS data set
named WORK.LOOP?
The answer given is X = 5, Index = 7
Can someone kindly enlighten me?
The do loop
DO index=1 to 5 by 2;
x=index;
end;
tells SAS to
So when index=5, the loop runs an iteration (and x=5). At the end of that iteration INDEX is incremented to 7, then SAS goes to the top for assessment of index. It exceeds 5, so the do loops are finished, leaving X=5.
Using put statements carefully between statements helps us to know what's happening during each iteration and why(logic aka the loop's exit)
data WORK.LOOP;
X = 0;
do Index = 1 to 5 by 2;
X = Index;
put x= index=;
end;
put index=;
run;
put x= index=;-->X=1 Index=1
put x= index=;-->X=3 Index=3
put x= index=;-->X=5 Index=5
put index=; -->Index=7 loops exit
Does this help at all?
@cow240wrote:
Thank you for your replies. Apologies for the newbie questions as im new to SAS. I just thought that intuitively, it should stop at 5 since it exits at 5. I guess I have a lot to learn!
No need for Apologies . There aint somebody who is more dumb than me when i started learning sas. Cheers!
The do loop
DO index=1 to 5 by 2;
x=index;
end;
tells SAS to
So when index=5, the loop runs an iteration (and x=5). At the end of that iteration INDEX is incremented to 7, then SAS goes to the top for assessment of index. It exceeds 5, so the do loops are finished, leaving X=5.
The question is very trivial and basic, however you @cow240 could mark one of the answer as accepted and answered
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.