mrgreenly
mrgreenly

Reputation: 13

Incrementing through an array in MIPs to add the contents

Right now I'm trying to add up all of the contents for two arrays and storing them into their respective variables. I need to use one function for both arrays. Right now, my biggest issue is actually incrementing the array in order to actually add the contents. I moved my variables for the array, the size, and the sum into $a0, $a1, and $a2. In the fucntion, I can't find any way to increment the array to add the next value to the sum.

.data

array1: .word   2,4,6,8
size1:  .word   16
array2: .word   1,3,5
size2:  .word   12
sum1:   .word   0
sum2:   .word   0

.text
.globl main

main: 
lw  $a0, array1
lw  $a1, size1
lw  $a2, sum1

jal sumArr




sumArr:
beq $t0,$a1,main    # Branch to main if the size of the array and the pointer are equal

add $a2,$a2,$a0 # Add the element in the array to the corresponding sum
addi    $t0,$t0,4   # Add 4 to the pointer in order to view the next element of the array
j   sumArr

Is what I have so far.

Upvotes: 0

Views: 1622

Answers (1)

Michael
Michael

Reputation: 58447

You seem to have misunderstood how to read from memory. You should load the address of array1 into $a0 using la:

la  $a0, array1

$a0 can now be said to point to the first element of array1. To read that element you would use lw (since each of your elements are words):

lw $t0, ($a0)

And to make $a0 point to the next element you add the size of a word to $a0:

addiu $a0, $a0, 4

Doing another lw $t0, ($a0) now would give you the second element, and so on.

Upvotes: 1

Related Questions