Write a LC-3 subroutine for printing “Hello” for N times. Write a main program to input N from the keyboard, call the subroutine and then output “Hello” for N times.
时间: 2024-02-13 07:02:46 浏览: 84
Sure, here's an example LC-3 subroutine and main program that accomplishes this task:
```
.ORIG x3000
; Subroutine to print "Hello" for N times
; Input: R1 = N
; Output: None
PRINT_HELLO ST R7, SAVE_R7 ; Save R7 on the stack
ADD R7, R7, #-2 ; Allocate space for local variable
STR R1, R7, #0 ; Store N in local variable
LD R0, HELLO ; Load address of "Hello" string into R0
AND R1, R1, #0 ; Clear R1
LOOP BRz END_LOOP ; Exit loop if R1 is 0
PUTS ; Print "Hello"
ADD R1, R1, #-1 ; Decrement loop counter
BR LOOP ; Repeat loop
END_LOOP LDR R1, R7, #0 ; Restore N from local variable
ADD R7, R7, #2 ; Deallocate space for local variable
LD R7, SAVE_R7 ; Restore R7 from the stack
RET
HELLO .STRINGZ "Hello\n"
SAVE_R7 .FILL x0000
; Main program to input N, call PRINT_HELLO, and output "Hello" for N times
; Input: None
; Output: None
MAIN LEA R0, PROMPT ; Prompt user for input
PUTS
GETC ; Read first character of input
OUT ; Echo input back to the console
AND R1, R1, #0 ; Clear R1
ADD R0, R0, #-10 ; Convert ASCII character to decimal value
ADD R1, R1, R0 ; Add decimal value to R1
GET_INPUT GETC ; Read next character of input
BRz CALL_PRINT ; Exit loop if user pressed Enter
OUT ; Echo input back to the console
ADD R0, R0, #-10 ; Convert ASCII character to decimal value
ADD R1, R1, R0 ; Add decimal value to R1
BR GET_INPUT ; Repeat loop
CALL_PRINT JSR PRINT_HELLO ; Call PRINT_HELLO subroutine
HALT
PROMPT .STRINGZ "Enter a number: "
```
Here's a brief description of how the code works:
1. The `PRINT_HELLO` subroutine takes a single input parameter `R1`, which represents the number of times to print "Hello". It saves the value of `R7` onto the stack, allocates space for a local variable, and stores `N` in the local variable.
2. The subroutine then enters a loop that prints "Hello" using the `PUTS` instruction, decrements the loop counter (`R1`), and repeats the loop until `R1` is zero.
3. After the loop completes, the subroutine restores the value of `N` from the local variable, deallocates the space for the local variable, restores `R7` from the stack, and returns control to the calling program.
4. The `MAIN` program prompts the user to enter a number `N`, reads the input from the keyboard, and converts the ASCII characters to a decimal value stored in `R1`.
5. The `MAIN` program then calls the `PRINT_HELLO` subroutine with `N` as the input parameter, which prints "Hello" `N` times.
6. Finally, the program halts execution.
Note that this code assumes that the LC-3 has a `PUTS` instruction for printing strings to the console. If `PUTS` is not available, you'll need to write your own subroutine to print characters or strings.
阅读全文