BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
vincentgoh88
Fluorite | Level 6

Hi,

 

Can anyone help me to understand why the final output x= 5 index = 7 appear?

 

Code:


data work.loop;
x = 0;
do index = 1 to 5 by 2;
x = index;
output;
end;
output;
run;

 Output: 

Capture.PNG

1 ACCEPTED SOLUTION

Accepted Solutions
RW9
Diamond | Level 26 RW9
Diamond | Level 26

Just simply follow the logic:

	do index = 1 to 5 by 2;
x = index;
output;
end;
output;

Index starts at 1, x is set to it.  Then it is output

Then 3, x is set to it.  Then it is output

Then 5, x is set to it, then it is output. 

Then index becomes 7, which does not work in the do, so the do loop is jumped, and then next step is output, which outputs the 7 record.  X remains as 5, as the part in the do loop is not executed.

 

View solution in original post

5 REPLIES 5
RW9
Diamond | Level 26 RW9
Diamond | Level 26

Just simply follow the logic:

	do index = 1 to 5 by 2;
x = index;
output;
end;
output;

Index starts at 1, x is set to it.  Then it is output

Then 3, x is set to it.  Then it is output

Then 5, x is set to it, then it is output. 

Then index becomes 7, which does not work in the do, so the do loop is jumped, and then next step is output, which outputs the 7 record.  X remains as 5, as the part in the do loop is not executed.

 

vincentgoh88
Fluorite | Level 6
Thanks!
Amir
PROC Star

Hi,

 

The do loop continues looping until the upper limit is exceeded, so after the loop has processed the index of 5, index is increased by 2 which becomes 7 which exceeds the upper limit of the loop and so it is not executed again; x is not reassigned again so it is left with its last value of 5.

 

Regards,

Amir.

Ksharp
Super User

After DO LOOP ,index will +2 by itself , therefore, the last index is 7 .

Kurt_Bremser
Super User

Basically all languages that I know implement iterative loops like that.

Only loops where the "index variable" is set from a list (eg see "for" in UNIX shell scripting) terminate differently.

sas-innovate-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

Register now!

How to Concatenate Values

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 5 replies
  • 662 views
  • 1 like
  • 5 in conversation