[SOLVED] Confusion with Little Man Computer; simple division program


This Content is from Stack Overflow. Question asked by Edrawrxd

        STA A
        STA B
        LDA 99
        STA C
loop    LDA A
        SUB B
        STA A
        LDA C
        ADD Y
        STA C
        LDA A
        BRP loop
        LDA C
A       DAT
B       DAT
C       DAT 
Y       DAT 1

Hello I am new to Little Man computer, this number division program should return 6 when A is input as 24 and B as 4, but when I run it, it outputs 7 which makes no sense. I know it loads A into the accumulator at the start and end of the while loop so I didn’t include that in the trace table. I’m not a credible user yet it makes me use links for pictures


Here are some issues:

  • BRP will also branch when the accumulator has zero, which explains why you get 7 instead of 6 for your test case.

  • Loading zero into the accumulator should better be done from a labeled mailbox, not from hardcoded 99. As HLT is zero, you could give that line the label zero and use LDA zero instead of LDA 99

  • Instead of A, B, C and Y use some more descriptive names, like numerator, divisor, quotient and one.

  • The way BRP works may differ a bit on different LMC emulators. To make sure you have the greatest compatibility, perform BRP immediately after SUB, because the value left in the accumulator after a SUB-overflow can be different on different emulators, and secondly, some emulators may reset the negative-flag when executing LDA, making BRP to always branch after LDA. By placing the BRP right after SUB you also solve the first problem.

Here is a runnable corrected version. It loads with your example input, but the little GUI allows you to test with other inputs:

#input: 24 4
          STA numerator
          STA divisor
          LDA zero
loop      STA quotient
          LDA numerator
          SUB divisor
          BRP continue
          LDA quotient
zero      HLT
continue  STA numerator
          LDA quotient
          ADD one
          BRA loop
numerator DAT
divisor   DAT
quotient  DAT
one       DAT 1

<script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.816/lmc.js"></script>

This Question was asked in StackOverflow by Edrawrxd and Answered by trincot It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?