I am trying to understand this SAS question and how the output statement works here. The question asks what the values of i and x are.
But when I add an output statement it shows 3 observations x 1,3,5 and i 1,3,5.
(I had thought of the output statement as writing the current values, but I'm not sure what that means here)
This is the code and explanation it gives,
data new;
x = 0;
do i = 1 to 5 by 2;
x = i;
end;
run;
Answer
x=5 i=7
Step check
1. x=0, i=1
2. x=1, i=3
3. x=3 i=5
4 x=5 i=7
The loop is correct. The DO loop terminates when the value is 7. So in the last iteration of the loop, i=5, then it increments in the DO statement, realizes it's past the interval for the loop and then terminates. X remains 5 because the loop was never entered, but i is 7.
If you add OUTPUT statements, note the plurality, then you can see it. Note I used PUT in the log to make the output easier to read.
data new;
x=0;
do i=1 to 5 by 2;
x=i;
output;
end;
output;
run;
Output:
69 data new;
70 file log dsd;
71 x = 0;
72 do i = 1 to 5 by 2;
73 x = i;
74 put _all_;
75 end;
76 put _all_;
77 run;
x=1 i=1 _ERROR_=0 _N_=1
x=3 i=3 _ERROR_=0 _N_=1
x=5 i=5 _ERROR_=0 _N_=1
x=5 i=7 _ERROR_=0 _N_=1