1

I need to print all digits of a given number in LMC. I tried with this code who gives me the last digit but I don't know how to keep going with the other digits.

    INP
L0  STA R0
    SUB R1
    BRP L0
    LDA R0
    OUT
    HLT
R0  DAT 000
R1  DAT 010
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
User28
  • 25
  • 2
  • 1
    You're doing `x % 10` to get the lowest digit. If you also do `x /= 10`, and then repeat, you can get all the digits (least-significant-first). Just like [How do I print an integer in Assembly Level Programming without printf from the c library?](https://stackoverflow.com/a/46301894). Since this is LMC, you do have to implement div/mod with a loop, so you'll need a nested loop. – Peter Cordes Nov 19 '20 at 01:56

1 Answers1

1

The code you have will output the least significant digit. To produce the other two digits (knowing that the LMC is limited to 3 digit numbers), first subtract 100 repeatedly and count how many times you could do that: this would be the first digit to output. Then subtract 10 repeatedly and count... and finally output the remainder.

For the repeated subtraction you need a loop. You could consider using self modifying code in order to reuse the same loop for subtracting 100 and later on for subtracting 10. But you might as well write a separate loop for each of these two cases:

#input:321
          INP
          STA input
          LDA zero   ; prepare for finding first digit
          BRA enter1

loop1     STA input
          LDA digit  ; increment digit
          ADD one
enter1    STA digit
          LDA input
          SUB hundred ; output number of 100s
          BRP loop1
          LDA digit
          OUT

          LDA zero   ; prepare for finding second digit
          BRA enter2

loop2     STA input
          LDA digit  ; increment digit
          ADD one
enter2    STA digit
          LDA input
          SUB ten
          BRP loop2
          LDA digit  ; output number of 10s
          OUT
          LDA input  ; output remainder
          OUT
zero      HLT

one       DAT 001
ten       DAT 010
hundred   DAT 100

input     DAT
digit     DAT

<script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.80/lmc.js"></script>
trincot
  • 317,000
  • 35
  • 244
  • 286
  • 1
    Thank you so much! I improved my code but I had some problem with the 0. I found the solution with your code !! – User28 Nov 19 '20 at 16:33