Explain why I am getting all the EVEN values when I am doing i+j as a final result in the nested loop:
data floyd;
array arr(*) col1-col5;
do i=1 to 5;
do j=1 to i;
arr(i) = i+j;
end;
output;
end;
drop i j;
run;
proc print; run;
As per my understanding output has to be :
Expected output:
and so on.........
Can anyone please explain.
No.
You seem to have confused which index variable represents the observation number (aka ROW) and which one represents the variable number (aka COLUMN).
It would also be clearer to empty the array after you write it to see what you are really doing.
data floyd;
array arr[*] col1-col5;
do i=1 to 5;
do j=1 to i;
arr[i] = i+j;
end;
output;
call missing(of arr[*]);
end;
drop i j;
run;
Result
Obs col1 col2 col3 col4 col5 1 2 . . . . 2 . 4 . . . 3 . . 6 . . 4 . . . 8 . 5 . . . . 10
So when I=2 you write two different values into ARR[2], so only the final one, 4, remains.
It becomes clearer is you use ROW and COL as the index variable names.
Now it become clearer that you wanted:
arr[col] = row+col;
Instead of
arr[row] = row+col;
Try
data floyd;
array arr[*] col1-col5;
do row=1 to 5;
do col=1 to row;
arr[col] = row+col;
end;
output;
end;
drop row col;
run;
proc print; run;
No.
You seem to have confused which index variable represents the observation number (aka ROW) and which one represents the variable number (aka COLUMN).
It would also be clearer to empty the array after you write it to see what you are really doing.
data floyd;
array arr[*] col1-col5;
do i=1 to 5;
do j=1 to i;
arr[i] = i+j;
end;
output;
call missing(of arr[*]);
end;
drop i j;
run;
Result
Obs col1 col2 col3 col4 col5 1 2 . . . . 2 . 4 . . . 3 . . 6 . . 4 . . . 8 . 5 . . . . 10
So when I=2 you write two different values into ARR[2], so only the final one, 4, remains.
It becomes clearer is you use ROW and COL as the index variable names.
Now it become clearer that you wanted:
arr[col] = row+col;
Instead of
arr[row] = row+col;
Try
data floyd;
array arr[*] col1-col5;
do row=1 to 5;
do col=1 to row;
arr[col] = row+col;
end;
output;
end;
drop row col;
run;
proc print; run;
Very depth explanation, Thank you.
Registration is open! SAS is returning to Vegas for an AI and analytics experience like no other! Whether you're an executive, manager, end user or SAS partner, SAS Innovate is designed for everyone on your team. Register for just $495 by 12/31/2023.
If you are interested in speaking, there is still time to submit a session idea. More details are posted on the website.
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.