.ORIG x3000
COUNTER .FILL x0005
LEA R0, HELLO_WORLD
PUTS
HALT
HELLO_WORLD .stringz "Hello World this is John Cena!"
.END
這是我到目前爲止只寫了一次這個名字的代碼,我很困惑如何在這段代碼中實現循環,這樣名字就會顯示5次。如何編寫一個打印出「Hello World」的程序,在LC3中使用循環5次?
.ORIG x3000
COUNTER .FILL x0005
LEA R0, HELLO_WORLD
PUTS
HALT
HELLO_WORLD .stringz "Hello World this is John Cena!"
.END
這是我到目前爲止只寫了一次這個名字的代碼,我很困惑如何在這段代碼中實現循環,這樣名字就會顯示5次。如何編寫一個打印出「Hello World」的程序,在LC3中使用循環5次?
完成此操作的最佳方法是使用for循環的等價物。我們的循環極限變量必須使用2的補碼反轉,這給了我們-5。然後,我們將循環計數加到-5以查看它們是否等於0.如果爲零,則跳出for循環。
.ORIG x3000
AND R1, R1, #0 ; clear R1, R1 is our loop count
LD R2, LIMIT ; load our loop max limit into R2
NOT R2, R2 ; Invert the bits in R2
ADD R2, R2, #1 ; because of 2's compliment we have
; to add 1 to R2 to get -5
FOR_LOOP
ADD R3, R1, R2 ; Adding R1, and R2 to see if they'll
; will equal zero
BRz LOOP_END ; If R1+R2=0 then we've looped 5
; times and need to exit
LEA R0, HELLO ; load our string pointer into R0
PUTs ; Print out the string in R0
LD R0, NEWLINE ; load the value of the newline
PUTc ; print a newline char
ADD R1, R1, #1 ; add one to our loop counter
BRnzp FOR_LOOP ; loop again
LOOP_END
HALT ; Trap x25
; Stored values
LIMIT .FILL x05 ; loop limit = 5
NEWLINE .FILL x0A ; ASCII char for a newline
HELLO .STRINGZ "Hello World, this is NAME!"
.END
我想用do while循環是LC3機器上容易得多。還有很多更少的編碼。
.ORIG x3000
AND R1,R1,#0 ;making sure register 1 has 0 before we start.
ADD R1,R1,#6 ;setting our counter to 6, i will explain why in a sec
LOOP LEA R0, HELLO_WORLD
ADD R1,R1,#-1 ;the counter is decremented before we start with the loop
BRZ DONE ;break condition and the start of the next process
PUTS
BR LOOP ;going back to the start of the loop while counter !=0
DONE HALT ;next process starts here, stopping the program
HELLO_WORLD .STRINGZ "HELLO WORLD\n"
.END
我的計數器設置爲6的原因是,它實際上被遞減真正開始循環之前,所以在循環開始的時候,它實際上5.我之所以這樣做是因爲BR指令被綁定到最後註冊你擺弄。如果要將其設置爲0,只需將具有ADD R1,R1,#6的行更改爲 ADD R1,R1,#5。將此循環更改爲此。
LOOP LEA R0, HELLO_WORLD
ADD R1, R1, #0
BRZ DONE
PUTS
ADD R1, R1, #-1
BR LOOP
希望這會有所幫助!
打印Hello World!使用循環5次:
; +++ Intro to LC-3 Programming Environment +++
; Print "Hello World!" 5 times
; Use Loops to achieve the aforementioned output
; Execution Phase
.ORIG x3000
LEA R0, HELLO ; R0 = "Hello....!"
LD R1, COUNTER ; R1 = 5
LOOP TRAP x22 ; Print Hello World
ADD R1, R1, #-1 ; Decrement Counter
BRp LOOP ; Returns to LOOP label until Counter is 0 (nonpositive)
HALT
; Non-Exec. phase
HELLO .STRINGZ "Hello World!\n" ; \n = new line
COUNTER .fill #5 ; Counter = 5
.END ; End Program
好運在你的作業和學習LC-3彙編語言! :D