Reputation: 93
I am on the following task in MARIE (Machine Simulator Environment):
Allow the user to input 2 numbers.
Compare them.
If the two numbers are the same: output a 1
If they aren't the same: output a 0.
So far I've got the bare minimum:
INPUT
STORE X
INPUT
STORE Y
HALT
X, DEC 010
Y, DEC 011
But I don't know what to do next. Which are the instructions to use for comparing the inputs for equality, and to output a different output (0 or 1) depending on that comparison?
Upvotes: 3
Views: 3598
Reputation: 350242
To compare numbers in MARIE for equality, you subtract them. After the subtraction you then check whether the result is 0, using SkipCond 400
.
You only need to store one of the inputs, as you can immediately subtract the first input from the second, without actually storing the second input.
To output 1 when the inputs are equal, and 0 otherwise, you can have two code blocks, one that loads the value of 0 and outputs it, and another that loads the value of 1 and outputs it, and then execute the one of these two blocks that is relevant. This is the approach taken in the answer of user3956566.
But you could also do this (in pseudo code):
Input X
Input Y
acc := X - Y
If acc != 0 Then
acc := -1
End If
acc := acc + 1
Output acc
After the if
has executed, you know that acc
will be either -1 or 0. Then it is easy to adapt that to 0 or 1 respectively.
In MARIE:
Input
Store X
Input
Subt X
SkipCond 400 / If difference is non-zero ...
Load MinusOne / ... then load -1
Subt MinusOne / In either case: add 1
Output
Halt
X, Dec 0
MinusOne, Dec -1
This is a rare case when you don't put a Jump
instruction right after a SkipCond
instruction.
Upvotes: 0
Reputation:
Have one variable to store input. Then subtract the next input from it. If the result is zero skip to print a 0. Otherwise print a 1 and then jump to the end of the program
Input
Store Num
Input
Subt Num
Skipcond 400
Jump Equal /If zero the numbers are equal
Load One
Output
Jump End
Equal, Load Zero
Output
End, Halt
/ declarations
Num, Dec 0
Zero, Dec 0
One, Dec 1
Upvotes: 1