I am working on this challenge:
The program needs to accept a sequence of integers. It ends with number 999. The integers (except 999) are placed in a list. The integers must be less than or equal to 99. Any inputs greater than 99 are not placed in the list.
If the input would have more than ten numbers, only the first ten are stored.
999 is not part of the output.
I don't know how to limit the list length to ten (10) numbers. Also I don't know how to output the list in reverse order.
This is my code:
start INP
STA temp
SUB big
BRZ doout
LDA temp
SUB hundred
BRP start
sub one
STA N
xx STA ARR
LDA xx
add one
sta xx
BRA start
doout HLT
temp dat 0
big dat 999
hundred dat 100
ARR dat
one dat 1
N dat 10
The xx
in your program show that you haven't taken the hint from How can I store an unknown number of inputs in different addresses in LMC (little-man-computer)?
It explains how you can have self-modifying code to walk through an array -- either to store values or to load them.
In your attempt there is no section that deals with outputting.
For the start section of the program I would actually suggest to subtract first the 100 and then 899 (which amounts to 999). That way you can keep the (reducing) input in the accumulator without having to restore it.
Also, due to an ambiguity in the specification of LMC, it is not entirely "safe" to do a BRZ
right after a SUB
(this is because the content of the accumulator is undefined/unspecified when there is underflow, so in theory it could be 0). You should always first do a BRP
before doing a BRZ
in the branched code. However, as input cannot be greater than 999, a BRP
is enough to detect equality.
For the self modifying part, you can set an end-marker in your array data section, and define the LDA
and STA
instructions that would read/store a value at the end of the array. Whenever your code has that exact instruction, you know you have reached the end.
Here is how it can work:
LDA store # Initialise dynamic store instruction
STA dyna1
loop INP
dyna1 STA array
SUB toobig
BRP skip
LDA dyna1
ADD one
STA dyna1
SUB staend
BRP print
BRA loop
skip SUB trailer
BRP print # Safer to do BRP than BRZ
BRA loop # Input was less than 999
print LDA dyna1 # Convert dynamic store instruction
SUB store # ... to index
ADD load # ... to load instruction
STA dyna2
loop2 LDA dyna2
SUB one
STA dyna2
SUB load
BRP dyna2
end HLT # all done
dyna2 LDA array
OUT
BRA loop2
store STA array
load LDA array
staend STA after
one DAT 1
toobig DAT 100
trailer DAT 899
array DAT
DAT
DAT
DAT
DAT
DAT
DAT
DAT
DAT
DAT
after DAT
<script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.816/lmc.js"></script>
As you can see (while running the script here), the instructions at dyna1
and dyna2
are modified during the execution of the loop they are in.