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-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
  • 4 replies
  • 819 views
  • 3 likes
  • 5 in conversation