Enigmatic
Enigmatic

Reputation: 4148

Why are these few lines of assembly code necessary for my program to function properly?

I have created a simple program on LMC that squares an input.

        INP
        STA X
        LDA X
        STA Y
LOOP    LDA Y
        BRZ END
        LDA ANSWER
        ADD X
        STA ANSWER
        LDA Y
        SUB ONE
        STA Y
        BRA LOOP
END     LDA ANSWER
        OUT
        SUB ANSWER - This line
        STA ANSWER - And this one
        HLT
ONE     DAT 1
ANSWER  DAT 0
X       DAT 
Y       DAT 

After some testing, I've noticed that without the two lines indicated above and below:

        SUB ANSWER - This line
        STA ANSWER - And this one

... the program doesn't seem to output the correct result. More specifically, the result produced is very spontaneous after running the simulator multiple times.

I ask this question out of curiosity since I don't seem to understand the point/reasoning of the lines I have added above to make the program work. I got it working purely out of luck.

Upvotes: 0

Views: 62

Answers (1)

loa_in_
loa_in_

Reputation: 1011

That's because when resetting the machine by pressing Reset button to provide another input for another run, the answer from previous calculations still is in RAM. The Reset button doesn't clear the memory nor reset it to state just after compilation, so the next Run just runs through memory as it was left by previous run.

The code you noted does nothing for the execution itself, other than zeroing the contents of ANSWER in memory before next iteration of algorithm. It does it through subracting value of ANSWER from the Accumulator (which contains ANSWER at the moment, giving zero) and SToring Accumulator into address ANSWER, effectively writing zero there.

To demonstrate this through running you program try this sequence:

  • Assemble your program without these two lines into memory
  • run it with a number 10 to the end
  • press reset
  • run it with a small number of your choice that you know the square of
  • the result should be 100 greater than expected
  • Assemble your program again
  • run it with a number 5 to the end
  • press reset
  • run it with a small number of your choice that you know the square of
  • the result should be 25 greater than expected

Upvotes: 1

Related Questions