DATA Step, Macro, Functions and more

do loop

Reply
Occasional Contributor
Posts: 9

do loop

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 ?

PROC Star
Posts: 513

Re: do loop

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

 

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

Super User
Super User
Posts: 9,599

Re: do loop

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.

PROC Star
Posts: 1,833

Re: do loop

@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

 

 

Trusted Advisor
Posts: 1,256

Re: do loop

Posted in reply to novinosrin

@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.

Ask a Question
Discussion stats
  • 4 replies
  • 80 views
  • 3 likes
  • 5 in conversation