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).
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.