I need a bit of help to code how to divide a sum of numbers, divided by n numbers put in. For instance, the sum is 10, with 2 numbers, the answer should be 5. But if the sum is 14 and the total input (n numbers) are 3, it should write out 4, ignoring the 2 remainders, og for example, sum equals to 16 and total inputs equal to 3, the output should be 5, ignoring the 1 in remainder. But I don't know how to have these two in one code without interfering with each other. This is my current code
START INP
BRZ SLUTT
ADD sum
STA sum
LDA antall
ADD en
STA antall
BRP START
SLUTT LDA sum
OUT
LDA linjeskift
OTC
OTC
OTC
LDA n
OTC
LDA likhetstegn
OTC
LDA antall
OUT
LDA linjeskift
OTC
OTC
OTC
LDA d
OTC
LDA likhetstegn
OTC
start LDA sum
BRZ slutt
SUB antall
STA sum
LDA resultat
ADD en
STA resultat
BRP start
slutt LDA resultat
OUT
HLT
sum DAT
resultat DAT 0
antall DAT 0
en DAT 1
a DAT 97
d DAT 100
n DAT 110
linjeskift DAT 13
likhetstegn DAT 61
The main problem is that your
BRPinstruction, in the division part of the code, comes too late. It is supposed to check whether the subtraction ofantallfromsumstill was non-negative, but as your code continues first by loading theresultatinto the accumulator, the detection of the negative result can no longer happen...BRPwill find that the latest operation (the update ofresultat) was non-negative.In short, that second part of the code should perform a
BRPright afterSUB. In LMC this is a general rule for doing it right: always have aBRPimmediately after aSUB.Some other comments:
BRZ sluttisn't really necessary anymore, as surely the nextSUBwill then return a negative result and trigger the output anyway. (but see next point)antall) is zero, we would be dividing by zero, which comes down to an infinite loop. This should be avoided by making an extra check.OTC. It seems unrelated to the goal of the challenge.sumorresultatto zero. It is therefore good practice to start the program with the initialisation of such "variables", so that the program will still behave correctly when the user uses the reset feature.BRPwhich really should always branch, so it would be more natural to useBRA. It also works withBRP, asantallwill not get negative, but it seems more intuitive to use the unconditional jump instruction here.Here is the updated code, with the above remarks taken into account: