Write a MIPS assembly language program that accomplishes the following: The prog
ID: 3908988 • Letter: W
Question
Write a MIPS assembly language program that accomplishes the following:
The program will prompt the user to enter an integer n between 0 and 10.
If n is out of range, the program displays an error message and prompts again
else
compute Func(n): if (n = 0 or n=1) return 5
else return 7*Func(n-2) – 8*n;
repeat
NOTE: use recursive function call.
You shouldn’t worry for very large values of n (the possibility of an overflow)
**** please include notes using # so that I can try to follow the steps being done
Explanation / Answer
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
.data
prompt: .asciiz "Enter value of n (rangge is 0 - 10): "
invalid: .ascii "Invalid value for n! Please try again"
message: .asciiz "The value of Func(n) = "
.text
loop:
#prompt and read int
li $v0, 4
la $a0, prompt
syscall
#read int and store in $t0
li $v0, 5
syscall
move $t0, $v0
bltz $t0, loop #if value is less than 0, go back to loop
bgt $t0, 10, loop #if value is more than 10, go back to loop
#now value is in range
#set up argument and call Func()
move $a0, $t0
jal Func
#get return value from $v0 and display
move $t0, $v0
li $v0, 4
la $a0, message
syscall
li $v0, 1
move $a0, $t0
syscall
#exit
li $v0, 10
syscall
#===========================
#Func() received n in $a0
Func:
#since it is recursive, save the value of argument $a0 and $ra on stack
sub $sp, $sp, 8 #allocate 8 bytes on stack
sw $a0, 0($sp)
sw $ra 4($sp)
#check for base case
beq $a0, 0, base_case
beq $a0, 1, base_case
#at this point $a0 is not 0 or 1
recursive_case:
#make a recursive call
#calculate Func(n-2)
sub $a0, $a0, 2
jal Func
#get return value
mul $v0, $v0, 7 # 7 * Func(n-2)
lw $t0, 0($sp) #get value of n from stack
mul $t0, $t0, 8 # 8 * n
sub $v0, $v0, $t0 # 7*Func(n-2) - 8*n
b end_Func
base_case:
li $v0, 5 # store 5 as return value
end_Func:
#restore registers
lw $a0, 0($sp)
lw $ra 4($sp)
add $sp, $sp, 8 #allocate 8 bytes on stack
jr $ra
output
====
Enter value of n (rangge is 0 - 10): -5
Enter value of n (rangge is 0 - 10): 12
Enter value of n (rangge is 0 - 10): 3
The value of Func(n) = 11
-- program is finished running --
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.