25.0k views
1 vote
write an lc-3 program that compares two numbers in r2 and r3 and puts the larger number in r1. if the numbers are equal, then r1 is set equal to 0.

1 Answer

3 votes

Answer:Here's an LC-3 program that accomplishes the task you described:

Step-by-step explanation:

vbnet

Copy code

ORIG x3000

AND R1, R1, #0 ; initialize R1 to 0

ADD R4, R2, #-1 ; subtract 1 from R2

ADD R5, R3, #-1 ; subtract 1 from R3

BRzp both_positive ; if both R2 and R3 are positive, go to both_positive

BRn R2_negative ; if R2 is negative, go to R2_negative

BRn R3_negative ; if R3 is negative, go to R3_negative

both_positive:

ADD R4, R4, R5 ; subtract R5 from R4

BRn R2_larger ; if R2 > R3, go to R2_larger

BRz equal ; if R2 = R3, go to equal

ADD R1, R3, #0 ; if R3 > R2, store R3 in R1

BRnzp done ; go to done

R2_negative:

ADD R4, R4, R5 ; subtract R5 from R4

BRn R2_larger ; if -R2 > R3, go to R2_larger

ADD R1, R3, #0 ; if R3 > -R2, store R3 in R1

BRnzp done ; go to done

R3_negative:

ADD R4, R4, R5 ; subtract R5 from R4

BRzp R2_larger ; if R2 > -R3, go to R2_larger

ADD R1, R2, #0 ; if -R3 > R2, store R2 in R1

BRnzp done ; go to done

R2_larger:

ADD R1, R2, #0 ; store R2 in R1

BRnzp done ; go to done

equal:

AND R1, R1, #0 ; store 0 in R1

BRnzp done ; go to done

done:

HALT

Here's how the program works:

Initialize R1 to 0.

Subtract 1 from R2 and R3 and store the result in R4 and R5, respectively. This is necessary because the LC-3 does not have a subtract instruction, so we have to add the two's complement of the second operand to the first operand to simulate subtraction.

Check if both R2 and R3 are positive. If they are, go to the both_positive label.

If R2 is negative, go to the R2_negative label.

If R3 is negative, go to the R3_negative label.

If both R2 and R3 are positive, subtract R3 from R2 and check the result to determine which number is larger.

If R2 is negative, add the two's complement of R2 to R3 and check the result to determine which number is larger.

If R3 is negative, add the two's complement of R3 to R2 and check the result to determine which number is larger.

Store the larger number in R1.

If the numbers are equal, store 0 in R1.

Halt the program.

Note that this program assumes that the numbers in R2 and R3 are signed 16-bit integers in two's complement format. If the numbers are unsigned, the program would need to be modified accordingly.

SPJ11

User AturSams
by
8.5k points