MIPS Assembler trouble - Arrays

430 views Asked by At

I have an assembly code containing an array, and I simply cannot understand what actually the result in the $s2 register shows. If someone could help and explain or simplify it for me that would be great. Here's the code:

.data     arr:     .word     3 2 -6 1 4 10 530 115 2231 1422
          arrSize: .word 10
.text
.global   main

main:
la        $s0, arr
la        $t0, arrSize
lw        $s1, 0($t0)
add       $s2, $zero, $zero

loop:
lw        $t1, 0($s0)
andi      $t2, $t1, 1
bne       $t2, $zero, skip
addi      $s2, $s2, 1

skip:
addi      $s0, $s0, 4
addi      $s1, $s1, -1
bne       $s1, $zero, loop  

end:
add       $v0, $zero, $s2
1

There are 1 answers

4
Paul R On BEST ANSWER

I've added some pseudo-code comments to the code:

.data     arr:     .word     3 2 -6 1 4 10 530 115 2231 1422
          arrSize: .word 10
.text
.global   main

main:

    la        $s0, arr            ;; s0 = arr          // init s0 = pointer to start of arr
    la        $t0, arrSize        ;; t0 = &arr_size    // get no of elements in arr
    lw        $s1, 0($t0)         ;; s1 = arr_size = 10
    add       $s2, $zero, $zero   ;; s2 = 0            // init count of even elements = 0

    loop:                         ;; do {              // for all elements in arr do
    lw        $t1, 0($s0)         ;;    t1 = *s0       //   get element from arr
    andi      $t2, $t1, 1         ;;    t2 = t1 & 1    //   test element for odd/even-ness
    bne       $t2, $zero, skip    ;;    if (t2 != 0)   //   if not odd (i.e. even) then
    addi      $s2, $s2, 1         ;;        s2++       //     increment count in s2

skip:
    addi      $s0, $s0, 4         ;;    s0++           //   increment pointer to next element in arr
    addi      $s1, $s1, -1        ;;    s1--           //   decrement count of elements to process
    bne       $s1, $zero, loop    ;; } while (s1 != 0) // end of do loop

end:
    add       $v0, $zero, $s2     ;; v0 = s2           // return result in v0

It seems that this just iterates through the elements of arr, testing each element to see if it is even, and incrementing a count of even elements found. The final result (in v0 and s2) will be 6, since there are 6 even elements in the array.