Write a program that reads a string from the user then prints it reversed.(by mi
ID: 3691266 • Letter: W
Question
Write a program that reads a string from the user then prints it reversed.(by mips assembly language)
Program Structure:
Input: a string.
Output: The string after reversing it. Definitions: Define a variable to hold the string. Algorithm:
1- Read string from user.
2- Initialize index by 0
3- Do:
4- Push string[index] in stack 5- Increment index
6- Repeat until string[index]=" " 7- Initialize index by 0 again
8- Do:
9- Pop from stack
10- Store in string[index]
11- Increment index
12- Repeat until stack empty 13- Print string
Sample Run:
Please enter a string: computer
The string after reversing it is : retupmoc
Explanation / Answer
Please follow the code and comments for description :
I'm trying to prompt the user for the length of a string, allocate space for that string, then print it out in reverse.
Code :
.data
nl: .asciiz " "
inputPrompt: .asciiz "Please enter an integer: "
theString: .space 32
theInteger: .word 1
.text
main:
la $a0, inputPrompt #load address a0 with prompt
li $v0, 4 #load system call, print string into v0
syscall
li $v0, 5 #load system call, read int into v0
syscall
sw $v0, theInteger #store saved int into $t0
li $v0, 8 #load system call, read string with mem address
la $a0, theString #load address of reserved string space
lw $a1, theInteger #load address of saved int length for string
syscall
lw $t0, theInteger
add $a1,$zero,$t0 #pass lenght of string
jal stringreverse #reverse the string
stringreverse:
add $t0,$a0,$zero #starting address
add $t1,$zero,$zero
add $t3,$zero,$zero #i = 0
addi $t2,$a1,-2 #j = length-1
loop:
add $t5,$t0,$t2
lb $t6,0($t5) #the lb string[j]
sb $t6,reverse($t3)
addi $t2,$t2,-1 #j--
addi $t3,$t3,+1 #i++
slt $t7,$t2,$t1
beqz $t7,loop
exit:
li $v1, 4 #system call to print reversed string
la $a2, 0($a1)
syscall
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.