How can I write a simple LC-3 program that compares the two numbers in R1 and R2 and puts the value 0 in R0 if R1 = R2, 1 if R1 > R2 and -1 if R1 < R2.
The comparison is done using simple arithmetic.
In my example we compare 2 and 6, you know what the result is.
LD R1, NUMBER1 ;load NUMBER1 into R1
LD R2, NUMBER2 ;load NUMBER1 into R2
AND R6,R6,#0 ;initialize R0 with 0
NOT R3, R2 ;R3 = -R2 (we negate NUMBER2)
ADD R4, R3, R1 ;R4 = R1 - R2
BRz Equals ;we jump to Equals if NUMBER1 = NUMBER2 (we can just jump directly to END)
BRn GreaterR2 ;we jump to GreaterR2 if NUMBER1 < NUMBER2
BRp GreaterR1 ;we jump to GreaterR2 if NUMBER1 > NUMBER2
Equals BRnzp End ;nothing to do, because R0=0 (THIS IS NOT NECCESARY)
GreaterR2 ADD R0, R0, #-1 ;R0 = -1
BRnzp End
GreaterR1 ADD R0, R0, #1 ;R0 = 1
BRnzp End
Done HALT ;THE END
NUMBER1 .FILL #2 ;/ Here we declare the numbers we want to compare
NUMBER1 .FILL #6 ;\