little-man-computer

LMC program do not output the correct sum


loop    inp
        sta numa
        sub validate
endthis brp loop
        bra label1
label1  lda numa
        sub validate1
        brp label2
        brz label2
endthis bra loop
label2  lda num
loop    sta num
        add total
        sta total
        sta num
        sub one
        brp loop
        lda total
        out
validate dat 11
validate1 dat 5
numa    dat
num     dat
total   dat 
one     dat 1

This program will let the user to input the number between 5 to 10 and calculate the sum of the numbers from 1 to the input specified by user and print the result in the output display. For example, if the user input 5, the sum will be 15.


Solution

  • There are the following issues with the code:

    There are also the following things to improve:

    Suggested solution:

              lda zero   # added: initialise total
              sta total
    getinput  inp
              sta input
              sub toogreat
              brp getinput
              lda input
              sub minimum
              brp inputok
              bra getinput
    inputok   lda input     # corrected
    loop      sta countdown
              add total
              sta total
              lda countdown # corrected
              sub one
              brp loop
              lda total
              out
              hlt   # added
    toogreat  dat 11
    minimum   dat 5
    input     dat 4
    countdown dat
    total     dat 0 
    zero      dat 0
    one       dat 1
    
    <script src="https://cdn.jsdelivr.net/gh/trincot/lmc@v0.816/lmc.js"></script>