# multiplication by recursive addition # implements the following C code # // x and y must be positive integers # // adds up the value x, y times, to produce (x * y) # int recmult( int x, int y) { # if( y == 0) return 0; # return( x + recmult( x, y-1); # } .data dataone: .word 12 datatwo: .word 7 datathree: .word 0 .text main: lw $a0, dataone # load the first argument lw $a1, datatwo # load the second argument jal recmult sw $v0, datathree # store the answer into datathree add $a0, $v0, $zero # put the answer into $a0 in prep for syscall print int li $v0, 1 # 1 in $v0 will make syscall to print_int syscall nop j end recmult: # First, push ra, s1 and s2 out onto the stack addi $sp, $sp, -12 # Putting 3 things onto the stack, so move the pointer down 12 bytes sw $s1, 8($sp) # Put the contents of $s1 out onto the stack memory sw $s0, 4($sp) # Put the contents of $s0 out onto the stack memory sw $ra, 0($sp) # Put the return address out onto the stack memory # Move our arguments (found in $a1 and $a2) into safe registers ($s0 and $s1) add $s0, $a0, $zero # Puts the $a0 value (the first argument) into $s0 add $s1, $a1, $zero # Puts the $a1 value into $s1 beq $s1, $zero, basecase # When y is zero return zero # Make the recursive call by loading $a0 and $a1 appropriately add $a0, $s0, $zero addi $a1, $s1, -1 jal recmult # The answer from the call to recmult is now in $v0 # Before we return, we must also put the answer into $v0 add $v0, $v0, $s0 # Adds our first argument to the recursive answer j restoreAndReturn # Jump to the return basecase: # In our basecase, just return 0 (put 0 into $v0) add $v0, $zero, $zero restoreAndReturn: # Put things back into registers from the stack lw $s1, 8($sp) lw $s0, 4($sp) lw $ra, 0($sp) addi $sp, $sp, 12 # Pop the stack (restore the stack pointer) jr $ra end: nop