Hello,
I am trying to understand the nested do loop concept. In this example, can we say inner do loop is repeated 2 times ?
data test;
do i = 1 to 2;
do j = 1 to 3;
output;
end;
end;
run;
Hi:
I agree, it depends on context and how you write the code. I think this comparison of the original do loop example and a modified version with i, j, and k loops in a different position explains how the iterations work -- 30 observations each time (because 2*3*5 or 5*2*3 or 3*2*5 will always equal 30), but the values fall into a different pattern.
cynthia
No. It's repeated 3 times
Also, inner/outer aren't always clear. Is J an inner or outer loop?
data test;
do i = 1 to 2;
do j = 1 to 3;
do k=1 to 5;
output;
end;
end;
end;
run;
@LinusH No idea, it probably depends on context. Just that as terminology goes, it's not definitive.
Hi:
I agree, it depends on context and how you write the code. I think this comparison of the original do loop example and a modified version with i, j, and k loops in a different position explains how the iterations work -- 30 observations each time (because 2*3*5 or 5*2*3 or 3*2*5 will always equal 30), but the values fall into a different pattern.
cynthia
One consideration is worth noting for efficiency purposes ... even though the inner loop executes 30 times in both cases, the total number of loops is different. The left-hand program is the most efficient order and executes a total of 38 loops (2 outer, 6 middle, 30 inner), while the right-hand program executes a total of 45 loops (5 outer, 10 middle, 30 inner). The least efficient order would put the fastest-moving variables on the outside:
do k=1 to 5;
do j=1 to 3;
do i=1 to 2;
end;
end;
end;
Now there are a total of 50 loops (5 outer, 15 middle, 30 inner).
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.
Ready to level-up your skills? Choose your own adventure.