Write a MIPS program that declares a string (with .asciiz) containing a fairly s
ID: 3589774 • Letter: W
Question
Write a MIPS program that declares a string (with .asciiz) containing a fairly short string, such as "The quick brown fox jumps over a lazy dog". .data str: .asciiz "The quick brown fox jumps over a lazy dog"
The program will reverse the string in place; that is, without copying it to another place in RAM. The basic algorithm is as follows:
Create 2 pointers, here called s and t (use registers)
Set pointer s to the start of the string.
Set pointer t to the end of the string
(scan for the '' terminator, then back up one place).
while( s < t )
swap *s and *t (here, * means "thing pointed to by" s and t)
increment s
decrement t end loop
A swap routine in a language like C needs a temporary location c, e.g.:
c = *t
*t = *s
*s = c
In C, *s means the thing pointed to by s. In assembler the registers you lb the bytes into can serve as the temporary location(s), so you don't need another location to hold a temporary value.
Explanation / Answer
Given below is the code for the question with output . Please don't forget to rate the answer if it helped. Thank you.
.data
str: .asciiz "The quick brown fox jumps over a lazy dog"
beforeMsg: .asciiz "The string before reverse is : "
afterMsg: .asciiz " The string after reverse is : "
.text
#display the string before reversing
li $v0, 4
la $a0, beforeMsg
syscall
li $v0, 4
la $a0, str
syscall
#=================
la $t0, str # t0 intially pointing to beginning of the string
la $t1, str #poiner to end of string, initially pointing to beginning
#make the end pointer reach the end of string
find_end:
lb $t2, ($t1) #get the char pointed by end pointer
beq $t2, '', found_end #if its end of string , then end pointer is indeed reached end
addi $t1, $t1, 1
b find_end
found_end:
#come back 1 location since its pointing to null terminator
sub $t1, $t1, 1
loop:
bge $t0, $t1, end_loop #if the begininng poiter is >= end pointer , we can stop
lb $t2, ($t0) #store beginning char in t2
lb $t3, ($t1) #store end char in $t3
#store the chars in exchanged positions
sb $t2, ($t1)
sb $t3, ($t0)
addi $t0, $t0, 1 #increment front pointer
sub $t1, $t1, 1 #decremetn back pointer
b loop
end_loop:
#display the string after reversing
li $v0, 4
la $a0, afterMsg
syscall
li $v0, 4
la $a0, str
syscall
#exit
li $v0, 10
syscall
outptu
The string before reverse is : The quick brown fox jumps over a lazy dog
The string after reverse is : god yzal a revo spmuj xof nworb kciuq ehT
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.