dsd
dsd

Reputation: 33

Trying to sum values of two arrays

I'm trying to sum the values of an "arrayA" with values of another "arrayB" and assign this sum in the same position where the index is in "arrayA", but the output is a result that I do not understand. Please, could someone help me?

Code:

.data
        arrayA: .word 1,12,35,473,2,32,4
        arrayB: .word 0,3,12,32,3,4,9
        length: .word 7
        count: .word 0
        line: .asciiz "\n"
        sum: .word 0
  .text
    MAIN:
        la $s1, arrayA 
        la $s2, arrayB 
        lw $t3, length
        li $t4, 0
        lw $t5, count
FOR: 
        beq $t3, $t4, EXIT
        lw $t0, ($s1)
        lw $t1, ($s2)
        add $t0, $t0, $t1
        sw $t0, ($s1)
        sw $t0, sum
        li $v0, 1
        la $a0, sum
        syscall
        li $v0, 4
        la $a0, line
        syscall
        addi $t4, $t4, 1
        addi $s1, $s1, 4
        addi $s2, $s2, 4
        j FOR
EXIT:
        li $v0, 10
        syscall

Output:

268501060
268501060
268501060
268501060
268501060
268501060
268501060

Upvotes: 0

Views: 844

Answers (1)

Michael
Michael

Reputation: 58447

$a0 is a different name for $4. So you're trying to use the same register for more than one thing at the same time (the address of the current element in arrayA, and the argument for a couple of system calls), which obviously doesn't work.

I'd suggest that you use a different register to hold the address of arrayA. And also to use the conventional register names ($v0, $a1, $t2, etc) at all times to avoid mistakes like these.


You're also using system call 1 incorrectly:

la $a0, sum

System call 1 expects the value to print to be placed in $a0, but you're placing the address of the value in $a0. Instead of la you should be using lw here. Of course, the sum variable is unncessary since you could've just added $t0 and $t1 into $a0 directly.

Upvotes: 2

Related Questions