Does not look like you need to use looping. Instead just use functions that can operate on multiple variables.
data have;
input q1-q20 flag_want;
datalines;
20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
20 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
20 0 -7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 -8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .
-8 -7 -7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .
-7 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1
;
data want;
set have;
if max(0,of q1-q20) > 0 then flag=1;
else if whichn(-7,of q1-q20)
or whichn(-8,of q1-q20)
or whichn(-9,of q1-q20)
then flag=.;
else if 0=min(0,of q1-q20)=max(0,of q1-q20) then flag=0;
run;
And perhaps if those special values, -7, -8 and -9 are the only valid values that are less then zero then the second IF can be simpler. For example you could use MIN() function.
else min(0,of q1-q20)<0 then flag=.;
Or if -7, -8 and -9 are really just different special missing codes if you actually code the data using special missing values (instead of valid numbers) you could use the NMISS() function. For example by using .A, .B, and .C instead of -7, -8 and -9.
missing abc ;
data have;
input q1-q20 flag_want;
datalines;
20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
20 20 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
20 0 A 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 B 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .
B A A 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .
A 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1
;
data want;
set have;
if max(0,of q1-q20) > 0 then flag=1;
else if 0<nmiss(of q1-q20) then flag=.;
else if 0=min(0,of q1-q20)=max(0,of q1-q20) then flag=0;
run;
... View more