Explain do loops

Solved
Occasional Contributor
Posts: 6

Explain do loops

Please can someone explain in details the data steps below and what each data statement is doing.

thanks

data work.invest;

do year = 2010 to 2014;

capital + 3000;

capital + (capital * 0.10);

end;

Accepted Solutions
Solution
‎10-22-2015 06:35 AM
Super User
Posts: 9,600

Re: Explain do loops

The do loop repeats the code within the block the number of times specified by the from and to (and step if supplied).

data work.invest;

do year = 2010 to 2014;

capital + 3000;

capital + (capital * 0.10);

end;

In your instance, the loop variable year runs from 2010 to 2014 (default step 1), so 2010, 2011, 2012, 2013.

You can expand the code to look like:

year=2010

add capital multiplied by 0.10 to capital

year=2011

add capital multiplied by 0.10 to capital

...

So year will end up as 2014, and capital will be the end result of those adds.

All Replies
Solution
‎10-22-2015 06:35 AM
Super User
Posts: 9,600

Re: Explain do loops

The do loop repeats the code within the block the number of times specified by the from and to (and step if supplied).

data work.invest;

do year = 2010 to 2014;

capital + 3000;

capital + (capital * 0.10);

end;

In your instance, the loop variable year runs from 2010 to 2014 (default step 1), so 2010, 2011, 2012, 2013.

You can expand the code to look like:

year=2010

add capital multiplied by 0.10 to capital

year=2011

add capital multiplied by 0.10 to capital

...

So year will end up as 2014, and capital will be the end result of those adds.

Occasional Contributor
Posts: 6

Re: Explain do loops

Thanks for your help. The explanation was very simplified and clear

Posts: 4,743

Re: Explain do loops

Is this an interview or study question?

Do you know SAS Language at all? Which bit of the code is not clear to you?

Here the documentation for a do-loop:

https://support.sas.com/documentation/cdl/en/lestmtsref/68024/HTML/default/viewer.htm#p1cydk5fq0u4bf...

Another good way to understand what's happening is to actually execute the code, look at the result and try to understand what's going on. Each "output" statement in below code will write a row to table "work.invest".

``````data work.invest;
do year = 2010 to 2014;
output;
capital + 3000;
output;
capital + (capital * 0.10);
output;
end;
run;``````
Occasional Contributor
Posts: 6

Re: Explain do loops

Am new to programming and am not sure about a lot of the statements. Thanks for your help

🔒 This topic is solved and locked.