In: Computer Science
Write a MIPS assembly language program to solve the following problem: For a set of integers stored in an array, calculate the sum of the even numbers and the sum of the odd numbers. The program should store these numbers in memory variables: evenSum and oddSum. Numbers should be read from the array one at a time with a zero value (0) being used to signal the end of data in the array.
The code will find the even / odd sum and store it in variables. You can see the screenshot of data segment that the sums are 0 initially and after code execution, the first 2 values in the data segment show the even sum and odd sum respectively.
.data
evenSum: .word 0
oddSum: .word 0
array: .word 20 11 4 8 7 5 3 9 1 2 0
.text
la $t0, array #get array address into t0
li $t1, 0 #even sum
li $t2, 0 #odd sum
li $t4, 2 #constant 2
Loop:
lw $t3, 0($t0) #get current int into t1
beqz $t3, EndLoop
div $t3, $t4 #divide by 2
mfhi $t5 #get the remainder of division
beqz $t5, Even
Odd:
add $t2, $t2, $t3
b Next
Even:
add $t1, $t1, $t3
Next:
add $t0, $t0, 4
b Loop
EndLoop:
#store the answers in variables
sw $t1, evenSum
sw $t2, oddSum
#exit
li $v0, 10
syscall
output
-----
Before executing code (after assembling)
After executing code