Trying to write a multiplication program for a hack computer and no matter which way I spin it I'm getting this comparison failure in the hardware simulator.
Can anyone point me in the right direction where to go with this? Is there something obvious I'm doing wrong?
Thank you!
@R0
D=M //load first number of equation into the d register from RAM[0]
@R2
M=0 //initialise RAM[2] a.k.a SUM to 0
(LOOP) //begin while loop
@R2
M=D+M //sum = D register value plus M register value
@R1
D=M // D register value is equal to the stored multiplication value i.e second number in the equation
D=D-A //de-increment the value in he d register by 1
@END
D;JLE //while loop break condition - if the value in the D register is less than or equal to zero, break loop
@R0
D=M //load the first number of the equation back into the D register
@LOOP
0;JMP //Loop back to the start of the while loop
(END)
@END // infinite loop
0;JMP
I've tried re-writing the code a few times with different logic, this way makes the most sense to me, but it still only gets through a few checks in the tst file
That code is failing to update R1, so it subtracts 1 to test for end condition, but leaves R1 with the original value.
So, needs M=D after D=D-A to update R1.
Suggest using -1 directly instead of -A, as the latter relies on the address of R1 being constant 1, which is a bit unexpected.
Maybe the following:
If it was me, I'd also load R0 closer to where it is being used rather than at the end of the loop to be used at the top of the loop.
This would then allow the loop to end with a conditional branch rather than an unconditional branch:
FYI, that construct you're using is a do-while loop not a while loop — the difference being the while loop iterates zero or more times, yet a do-while always iterates at least once (by "iterates" I mean runs the body of the loop: an iteration is a running of the loop body, here summing the multiplier). The effect is that if R1 is 0 for starters, a while loop will work properly whereas a do-while will not.
To fix this, you can keep the do-while form as it is a bit more efficient that the while form, but add an extra test for R1=0 at the beginning, before and outside the loop, to skip the entire loop if R1=0 is true.