Hi I'm trying to write a lc3 assembly program which computes the square of a number and stores it in r0, the integer is given as a parameter and is located in r1, the problem i noticed while debugging is during the first pass it initially adds 2, but the second pass it fails to add another 2 to r0 - My code is below any help is appreciated
.orig x3FF8
ld r1,n
ld r5,n
square
add r2,r1,#0
add r5,r5,#-1
add r0,r2,#0
brzp square
brn theend
theend
halt
n .fill #2
.end
my final code thanks to the user who helped:
.orig x3FF8
ld r1,n
ld r5,n
square
add r2, r2,r1
add r5,r5,#-1
brp square
theend
halt
n .fill #4
.end
If I remember LC-3 syntax correctly,
add r2,r1,#0
doesr2 = r1 + 0
, so it was never actually adding tor2
, just overwriting it withr1
.You want something like that outside the loop to initialize
r2
.But inside the loop, you want
add r2, r2, r1
which doesr2 = r2 + r1
, i.e.r2 += r1
.I don't understand why you have
add r0,r2,#0
inside the loop as well. If you want the final result inr0
, accumulate it inr0
in the first place. Of if that was supposed to be a sum of sums, then you have the same bug.Also note that
add r5,r5,#-1
needs to be last so condition code flags are set from it for the loop branch, not fromadd r0, r0, r2
or whatever else you need inside the loop.Also:
brn theend
is totally useless:theend
is on the next line, and execution continues to the next line on its own. You don't have to jump over whitespace in the source!