Search code examples
loopsassemblymips

I need help to SUM an array with 5 distinct values in assembly


the problem is that after the second index value it stops, so it goes -> array[0] + array[1] -> gets stuck here causing to the output to be 1...3 and forever 3 :(

this is my code by now:

.data
c:.word 1,2,3,4,5

.text

    la $s2, c
    li $t2, 0

loop:        



    add $t2, $t2, $t2 # 2*i
    add $t2, $t2, $t2 # 4*i
    add $t1, $t2, $s2 # a[i] = (4*i + $s2)
    lw  $t0, 0($t1)   # $t1 = a[i]
    add $s0, $s0, $t0 # g = h + a[i]

    li $v0, 1
    la $a0, ($s0)
    syscall

    add $t2, $t2, 1
    beq $s0, 15, endLoop

    j loop

endLoop:

    li $v0, 1
    la $a0, ($s0)
    syscall

Solution

  • .data
    c: .word 1,1,1,1,1
    
    .text
        la $s2, c
        li $t2, 0
        li $t5, 0
    
    loop:        
        add $t2, $t2, $t2 # 2*i
        add $t2, $t2, $t2 # 4*i
        add $t1, $t2, $s2 # a[i] = (4*i + $s2)
        lw  $t0, 0($t1)   # $t1 = a[i]
        add $s0, $s0, $t0 # g = h + a[i]
    
        li $v0, 1
        la $a0, ($s0)
        syscall
    
        add $t5, $t5, 1
        add $s2, $s2, 4
        beq $t5, 5 , fimLoop
    
        j loop
    
    fimLoop:
    
        li $v0, 1
        la $a0, ($s0)
        syscall