Mips programming question. Please include comments. Write a program that asks th
ID: 3865661 • Letter: M
Question
Mips programming question.
Please include comments. Write a program that asks the user to input a string (or no more than 50 characters). Your program should then output the length of the string. The string length should be determined using a separate function strlen that will accept the address of the string and return its length. For the purposes of this exercise, the length of a string will be defined as the number of non-null and non-newline characters until either the null character (ASCII 0) or the newline character (ASCII 10) is encountered.
Explanation / Answer
Given below is the code for calculating string length. Please don't forget to rate the answer if it helped. Thank you.
.data
prompt: .asciiz "Enter a string: "
str: .space 50
msg: .asciiz "The length of the string is "
.text
main:
#prompt the user
la $a0, prompt
li $v0, 4
syscall
#read the input
la $a0, str
li $a1, 50
li $v0, 8
syscall
#call the function strlen, address of string is already in $a0, lenght returned in $t1
jal strlen
#display result
li $v0, 4
la $a0, msg
syscall
li $v0, 1
move $a0, $t1
syscall
#exit
li $v0, 10
syscall
strlen:
move $t1, $zero #initialize counter t1 to zero
strlen_loop:
lb $t0, ($a0) #get the character into t0
beq $t0, 0, strlen_end #check if its null character
beq $t0, ' ', strlen_end #check if its newline
addi $t1, $t1, 1 #increment counter
addi $a0, $a0, 1
b strlen_loop
strlen_end:
jr $ra
output
Enter a string: Good morning
The length of the string is 12
-- program is finished running --
Enter a string: Hello World
The length of the string is 11
-- program is finished running --