.ORIG x3000
; program to replace each element A[i] in an array (list) with A[i]= X- A[i] 
; array has positive numbers, and end of array is when the array element is zero or negative

    
; Load X from memory to register R4
    LD R2, X    ; we load into R2 since we want to call SUB with X in R2
    LEA R0, msg1    ; load prompt message
    PUTS    ; print  message
    ; starting processing the array - subtract  each element from X (in R4)
    LD R6, Array    ; load starting address of array into R6
    
Loop    LDR R1, R6, #0  ; load first element into R2, R6 is address of array element
        BRnz done       ; if array element is not positive then exit the while loop
        LD R4, goSUB    ; load address of SUB subroutine into register R4
        JSRR R4    ; call subtract subroutine - inputs are in R1, R2 and it will return result in R3
; since SUB is close enough (within 11 bit offset) to the callign instruction, you can also use JSR SUB
; and the two instructions LD R4, goSUB and JSRR R4 will be replaced by a single instruction JSR SUB
        STR R3, R6, #0  ; store result back into array
        ADD R6, R6, #1  ; increment array address so it points to next element
        BRnzp Loop    ; repeat loop 
done    HALT    ;end program
;
Array   .FILL x4000     ; array starts at address x4000, initialize label Array to x4000
X   .FILL #100   ; define and initialize variable X to 100
msg1    .STRINGZ "starting loop"
goSUB   .FILL   SUB ; initialize variable goSUB to the address/label of subroutine SUB
; subroutine SUB - returns R3= R2-R1 
SUB     NOT R0, R1  ; complement R1 and store into R0
        ADD R0,R0, #1   ; 2's complement of R1 is now in R0
        ADD R3, R0, R2  ; compute R2+R0 = R2-R1 and store into R3
        RET ;return to caller
    ;
    .END
.ORIG x4000
.FILL #10
.FILL #20
.FILL #30
.FILL #40
.FILL #50
.FILL #60
.FILL #0
.FILL #10
.END