Mars4 5.jar: MARS MIPS simulator Download of Mars4.5: http://courses.missourista
ID: 3739538 • Letter: M
Question
Mars4 5.jar: MARS MIPS simulator
Download of Mars4.5:
http://courses.missouristate.edu/KenVollmar/mars/download.htm
P7.asm
# Problem 7: subroutine 2
# Write a subroutine "sum" that takes an integer n as input and
# return 1+2+...+n. The subroutine should calculate the sum by
# calling itself recursively, i.e., sum(n) = n + sum(n-1). The
# assembly code should be equivalent to the following C program.
#
# int sum(int n) {
# if (n == 1) return 1;
# else return n + sum(n - 1);
# }
#
# int main() {
# return sum(10);
# }
#
# write your code here
Problem 7: subroutine 2 Write a subroutine sum that takes an integer n as input and return ? 1 . The subroutine should calculate the sum by calling itself recursively, i.e. sum(n) -n + sum(n-1). The assembly code should perform equivalently to the following C program int sum(int n) ( if (n1) return1; else return n + sum(n - 1) int main ) return sum (10) Save the result of sum (10) in the register $to.Explanation / Answer
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
.data
msg: .asciiz "The sum is "
.text
#set up parameters and call the subroutine sum
li $a0, 10
jal sum
move $t0, $v0 #store the return value in $t0
#display the value from $t0
li $v0, 4
la $a0, msg
syscall
li $v0, 1
move $a0, $t0
syscall
#exit
li $v0, 10
syscall
#recursive sum routine
sum:
#save the argument $a0 and $ra on stack
sub $sp, $sp, 8
sw $a0, 0($sp)
sw $ra, 4($sp)
beq $a0, 1, base_case
sub $a0, $a0, 1
jal sum
lw $t0, 0($sp) #get the value of $a0 saved on stack
add $v0, $t0, $v0 #add the argument to return value n + sum(n-1)
b end_sum
base_case:
li $v0, 1
end_sum:
#restore values
lw $a0, 0($sp)
lw $ra, 4($sp)
add $sp, $sp, 8
jr $ra
======
output
======
The sum is 55
-- 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.