CSE 420: Computer Architecture 1
Module 1 Sample Questions
Question 1 (15 points) (10 mins) [MIPS Assembly Language Programming]
Write MIPS assembly language program for the AddOddElement routine shown
below. This ro
...
CSE 420: Computer Architecture 1
Module 1 Sample Questions
Question 1 (15 points) (10 mins) [MIPS Assembly Language Programming]
Write MIPS assembly language program for the AddOddElement routine shown
below. This routine sums only the odd elements of an array. You should write a
recursive function, similar to the one below. Stick to MIPS calling and register
conventions as much as possible.
Hint: You can check your solution by trying it out on MARS.
int AddOddElement( int arr[], int size ) {
if ( size == 0 )
return 0 ;
else if ( arr[ size - 1 ] % 2 == 1 )
return AddOddElement( arr, size - 1 ) + arr[ size - 1 ] ;
else
return AddOddElement( arr, size - 1 ) ;
}
Answer:
Usually, the hard part is to decide what registers to save. arr is stored in $a0, and that
this value really doesn't change throughout. size may need to be saved, though size - 1
appears to be more useful. Since we make calls to AddOddElement, we need to save
$ra.
So, let's save size - 1 and $ra to the stack. It turns out we also need to save arr[ size -
1 ] to the stack too.
AddOddElement: addi $sp, $sp, -12 # Adjust sp
addi $t0, $a0, -1 # Compute size - 1
sw $t0, 0($sp) # Save size - 1 to stack
sw $ra, 4($sp) # Save return address
bne $a0, $zero, CASE1 # branch !( size == 0 )
li $v0, 0 # Set return value to 0
addi $sp, $sp, 12 # Adjust sp
jr $ra # Return
CASE1: li $t7, 4 # t7 = 4
multi $t0, t7 # Multiple size - 1 by 4
mflo $t1 # Put result in t1
add $t1, $t1, $a0 # Compute & arr[ size - 1 ]
lw $t2, 0($t1) # t2 = arr[ size - 1 ]
andi $t3, $t2, 1 # is arr[ size - 1 ] odd
beq $t3, $zero, CASE2 # branch if even
sw $t2, 8($sp) # save arr[ size - 1 ] on stack
move $a1, $t0 # update second arg
jal AddOddElement
lw $t2, 8($sp) # restore arr[ size - 1 ] from stack
add $v0, $v0, $t2 # update return valuelw $ra, 4($sp) # restore return address from stack
addi $sp, $sp, 12 # Adjust sp
jr $ra # Return
[Show More]