assemblymipsqtspim

MIPS : summing the elements of two arrays


I am trying to perform the following function in QtSpim: A[i] = B[i] + C[i]

     .data
atable: .byte 0, 0, 0, 0
btable: .byte 10, 5, 5, 20
ctable: .byte 10, 4, 5, 1
spa: .byte 32

        .text
    .globl main

main:
    add $t4, $zero, $zero   # i is initialized to 0, $t4 = 0
    la $t0, atable 
    la $t1, btable
    la $t2, ctable
Loop:
    add $t5, $t4, $t1      # $t5 = address of b[i]
    lw $t6, 0($t5)         # $t6 = b[i]
    add $t5, $t4, $t2      # $t5 = address of c[i]
    lw $t7, 0($t5)         # $t7 = c[i]
    add $t6, $t6, $t7      # $t6 = b[i] + c[i]
    add $t5, $t4, $t0      # $t5 = address of a[i]
    sw $t6, 0($t5)         # a[i] = b[i] + c[i]
   
 li $v0,1
    move $a0,$t6        # $t0 = $t1 $a0,$t6
    syscall
  
  li $v0,4
    la $a1,spa
    syscall
    
addi $t4, $t4, 4       # i = i + 4
    slti $t5, $t4, 4       # $t5 = 1 if $t4 < 5, i.e. i < 2
    bne $t5, $zero, Loop   # go to Loop if i < 5
    
jr $ra
    # alternate exit
    exit:
    li $v0, 10
    syscall

The result of the execution of the above code is both a "Memory out of bounds error" message and this output in my console : 352979220(null)

I'm pretty sure that there is a problem with printing the values and the newline escape sequence (/n) , but I believe there is more than that because my code didn't work before I added the printing syscalls.

Any suggestions?


Solution

  • After some modifications :

              .data
        atable: .word 0, 0, 0, 0  # integers array (32 bits or 4 bytes each one)
        btable: .word 10, 5, 5, 20
        ctable: .word 10, 4, 5, 1
        spa: .asciiz " "
    
                .text
            .globl main
    
        main:
    
            la $t0, atable 
            la $t1, btable
            la $t2, ctable
            li $s0,0        # counter initialized to 0
        Loop:
    
            lw $t6, ($t1)         # $t6 = b[i]
    
            lw $t7, ($t2)         # $t7 = c[i]
            add $t8, $t6, $t7      # $t8 = b[i] + c[i]
    
            sw $t8, ($t0)         # a[i] = b[i] + c[i]
           
         li $v0,1
            move $a0,$t8        # $a0 = b[i]+c[i]
            syscall
          
          li $v0,4
            la $a0,spa
            syscall
            
        addi $t1, $t1, 4       # b[i++]
        addi $t2,$t2,4         # c[i++]
        addi $t0,$t0,4         # a[i++]
            addi $s0,$s0,1      # count = count+1
            blt $s0, 4, Loop   # go to Loop if count < 4
            
            # alternate exit
            exit:
            li $v0, 10
            syscall