Generally we have 4 status flags- Carry flag (C), Zero flag (Ze), Sign flag (S) and Overflow flag (V).
We will consider the given values are unsigned. For unsigned number comparison 2 flags are needed- Zero flag (Ze) and Carry flag (C).
I have used 'Ze' flag to distinguish between Z mentioned in code and Zero flag.
(A)
R1= 5= 101
R2=000
R3=000
Going step by step-
CMP R1,0; means 101-000= 101. Set the flags as Ze=0 and C=0.
JZ Z; means if Ze true then jump to Z. Since Ze is 0 ie false so don't jump.
MOV R2,R1; means R2= 101
SHR R1; R1 becomes 010
SHL R1; R1 becomes 100
CMP R2,R1; means 101-100= 001, set the flags as Ze=0 and C=0
JZ Y; means if Ze is 1 then jump to Y. Since Ze is 0 so don't jump.
INC R3; means R3 becomes 001.
SHR R1; R1 becomes 010
JMP X; go to X
Again start
CMP R1,0; 010-000=010, Set Ze= 0 and C =0
JZ Z; false
MOV R1, R2; R2 becomes 010
SHR R1; R1 becomes 001
SHL R1; R1 becomes 010
CMP R2,R1; means 010-010= 000 , set Ze=1 and C= 0
JZ Y; Ze is 1 so true, so jump to Y
SHR R1; R1 becomes 001
JMP X; Jump to X
Again start
CMP R1,0; 001-000= 001. Set Ze= 0
JZ Z; Ze= 0 so don't jump.
MOV R2,R1; R2 becomes 001
SHR R1; R1 is 000
SHL R1; R1 is 000
CMP R2,R1; 001-000 = 001 and set Ze=0 and C =0
JZ Y; false
INC R3; R3 becomes 010
SHR R1; R1 becomes 000
JMP X; go to X
Again
CMP R1 ,0; 000-000 = 000 Set flags Ze=1, C= 0.
JZ Z; Since Ze flag is true so jump to Z
So final values of R1= 0 and R3= 010= 2.
(B) Following the code carefully we see that R3 is incremented if R1 is not 0 or if the shift right and shift left operations make R1 different from R2. It is only possible when LSB of R1 had 1. So R3 is able to count number of 1's in R1.