I would like to know, why this code gives an error: invalid TRAP executed. Isn't the code correct? The input of a decimal is registered in R0 and if the number is prime, R0 will contain 1 at the end of the program and if the input_value is not prime, R0 will contain 0.
.ORIG x3000
LD R0, INPUT_NUMBER ; Load the input number directly into R0
AND R2, R0, #0 ; Clear R2 to use for comparisons
ADD R2, R0, #-1 ; Adjust for checking if input is 0 or 1
BRz IS_NOT_PRIME ; If input is 0, it's not prime
BRn CONTINUE_CHECK ; If input is negative, skip to array check (not possible in this context, but good practice)
ADD R2, R2, #1 ; Adjust R2 back for normal processing
CONTINUE_CHECK:
LEA R3, PRIME_ARRAY ; Load the address of the prime array into R3
ADD R3, R3, R0 ; Calculate the address to check in the array (using R0's value directly)
LDR R4, R3, #0 ; Load the value at that index into R4
BRz IS_NOT_PRIME ; If the value is 0, it's not prime
; If the value is 1, it's prime
LD R0, PRIME_VAL ; Set R0 to 1 to indicate prime
LEA R1, PRIME_MSG ; Load address of prime message into R1
PUTS ; Print the prime message
BR FINISH ; We are done
IS_NOT_PRIME:
AND R0, R0, #0 ; Set R0 to 0 to indicate not prime
LEA R1, NOT_PRIME_MSG ; Load address of not prime message into R1
PUTS ; Print the not prime message
FINISH:
HALT ; Stop the program
; Data section
INPUT_NUMBER .FILL #3 ; Test value (change this to the number to test)
PRIME_VAL .FILL #1 ; Value to indicate prime
NOT_PRIME_MSG .STRINGZ "0\n" ; Message for not prime number
PRIME_MSG .STRINGZ "1\n" ; Message for prime number
PRIME_ARRAY .FILL #0 ; 0 is not prime
.FILL #0 ; 1 is not prime
.FILL #1 ; 2 is prime
.FILL #1 ; 3 is prime
.FILL #0 ; 4 is not prime
.FILL #1 ; 5 is prime
; Continue for numbers 6-99 if needed
.END
I tested the code in WebLC3 Simulator, and it gives an error, invalid TRAP executed.
You have incorrect usage of
PUTS. FYI,PUTSis shorthandTRAP #22.PUTSrequires the address of null-character terminated string to print goes inR0, and that's the only register used to pass parameter toputs. (By passing 0 or 1 toPUTS(i.e. inR0) as you're doing now, it will fail in some manner.)Since
R0is necessarily used/repurposed to pass a parameter (address of string to print) toPUTS, then if the intent is to leave the program (atHALT) withR0as holding 0 or 1 (depending on the prime result), you will then obviously need to setR0after thePUTStrap.