Reputation: 141
I need to output the absolute value of the difference between two values. I have this code written in MARIE assembly language:
Org 100
Load X
Subt Y
Store Z
if, Skipcond 000
Jump Else
Then, Clear
ADD Z
Else, Output
Halt
X, DEC 10
Y, DEC 15
Z, DEC 10
When I run this code, it gives the output = FFFB, and I don't know how the output becomes FFFB because in the Skipcond 000
instruction we should skip the Jump Else
instruction (as the AC value is negative) and go to the Clear
instruction which will make the AC = 0 and then Add Z
which will make the value of AC = 10 in decimal or A in hexa.
What am I missing here?
Upvotes: 2
Views: 2425
Reputation: 350252
The cause is that your initial code updates Z
. This means that ADD Z
will not make the accumulator 10 as you state. By that time Z
no longer has its initial value of 10, but has a negative number, and so that is also what you output.
If you leave out the instruction Store Z
, it will do what you described.
But if you want to print the absolute value of X-Y
, then realise that if this difference is negative, and you store it in Z
, you actually want to negate the value of Z
, which you do by subtracting Z
from 0, not adding it.
Unrelated, but the label Else
is misleading, because the code there is also executed after the If
block. Calling it EndIf
seems more appropriate:
Load X
Subt Y
Store Z
if, Skipcond 000 / If Z < 0, go to Then
Jump EndIf / Else don't modify AC
Then, Clear
Subt Z / Now the AC will have positive value!
EndIf, Output
Halt
/ Input
X, Dec 10
Y, Dec 15
/ Temporary variable
Z, Dec 0
Now the output will be 5, which indeed is |10-15|.
Upvotes: 2
Reputation: 1
You might want to use Skipcond 800 instead of Skipcond 000. That's what makes the program wrong. Or you can change the values of all the variables to DEC 10
Upvotes: -1