## Do loop iterative statement expression evaluation?

Frequent Contributor
Posts: 75

# Do loop iterative statement expression evaluation?

Hi, I am finding it difficult to understand "how and when" the while or until expression is evaluated or checked in a iterative do loop statement. The documentation says something the optional while or until only evaluates when the index variable value happens to be the last item or something like that and in another google search I found either the index or the expression whichever comes first.

do index-variable= start to stop by increment while(expression) or until(expression);

Can someone please clarify my understanding. Thanks

Frequent Contributor
Posts: 77

## Re: Do loop iterative statement expression evaluation?

The main difference between while and until is

In while : the loop stops iterating when the condition is false

In until : the loop stops iterating when the condition is true.

For example : you want to display 5 consecutive numbers.

data Sample;

i = 1;

do while (i <= 5);

output;

i+1;

end;

output;

run;

In the above program we are initializing a value (1) to the variable i. So i = 1.

now the do loop starts.

checks the condition i <= 5 i.e 1 <=5 .

the condition is true.

1.now it enters the loop and executes the statements.

2.first it puts the value of i to the dataset and then the value of i will be incremented.

now the value of i is 2.

it goes to the top of the loop and again checks the condition i<=5 i.e i<=2

the condition is true. so step 1 and 2 are executed and now the value of i becomes 3

it goes to the top of the loop and again checks the condition i<=5 i.e i<=3

the condition is true. so step 1 and 2 are executed and now the value of i becomes 4

it goes to the top of the loop and again checks the condition i<=5 i.e i<=4

the condition is true. so step 1 and 2 are executed and now the value of i becomes 5

it goes to the top of the loop and again checks the condition i<=5 i.e i<=5

the condition is true. so step 1 and 2 are executed and now the value of i becomes 6

it goes to the top of the loop and again checks the condition i<=5 i.e i<=6... the condition is false so it comes out of the loop and then executes the remaining statements after end.

The next statement is output.

Now again the value of i is inserted to the Dataset.

After terminating from the do loop the value of i is 6. So 6 will be inserted in the dataset.

If we dont insert the output statement after the do loop then only 5 observation will be there in the dataset.

So the while loop executes until the condition is false.

In the same way until executes until the condion is true.

The only change in the code is in the condition

for while :

do while (i<=5);       ------------ Loop will be iterated until the value is less than or equal to 5

----;

end;

for until :

do until(i>5);           ------------ Loop will be iterated until the value is greater than 5

-----;

end;

Discussion stats