assemblydigitslittle-man-computer

Print all digits of a given number in LMC


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

Solution

  • 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>