BookmarkSubscribeRSS Feed
sanyam13
Fluorite | Level 6

data test;
do year = 1 to 5;
do month = 1 to 12;
x+1;
output;
end;
end;
run;

 

can somebody explain how this nested loop works , how I m getting 60 observations  in output ?

4 REPLIES 4
kiranv_
Rhodochrosite | Level 12

see the below link, it clearly explains about nesting loops.

 

https://onlinecourses.science.psu.edu/stat481/node/42/

RW9
Diamond | Level 26 RW9
Diamond | Level 26

Break it down:


do year = 1 to 5;   < - do this code 5 times
   do month = 1 to 12;
     x+1;
    output;
  end;
end;

For each of those five times:

   do month = 1 to 12;  <- do this code 12 times

     x+1;
    output;

 

Thus you are running 12 times (inner loop) for each of the 5 times (outer loop) = 60 iterations.

novinosrin
Tourmaline | Level 20

@sanyam13  A quick way to grasp the way my professor taught me a loop construct in any programming language 

 

1. inner most look executes in full and followed by one  by one to reverse top order

2. total number of loops processed = stopvalue1*stopvalue2*stopvalueN= 5*12=60  in your case

 

 

FreelanceReinh
Jade | Level 19

@novinosrin wrote:

 

2. total number of loops processed = stopvalue1*stopvalue2*stopvalueN= 5*12=60  in your case 


@sanyam13: It goes without saying that "stop value" in the above calculation does not always equal the value following the TO keyword (such as 10 in do i=1 to 10), but can differ from that value in many ways depending on start value (do i=0 to 10), increment (do i=1 to 10 by 2), WHILE/UNTIL conditions, the code performed in the loop (e.g. LEAVE statement), etc.

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 1114 views
  • 3 likes
  • 5 in conversation