[prev] 19 [next]

2-d Arrays in MIPS (cont)

Computing sum of all elements for strategy (b)  int matrix[4][4]

   li  $s0, 0             # sum = 0
   li  $s1, 4             # s1 = 4 (sizeof(int))
   li  $s2, 0             # row = 0
loop1:
   bge  $s2, $s1, end1    # if (row >= 4) break
   li   $s3, 0            # col = 0
   mul  $t0, $s2, $s1     # off = row*addrSize
   lw   $s4, matrix($t0)  # rowp = &matrix[row][0]
loop2:
   bge  $s3, $s1, end2    # if (col >= 4) break
   mul  $t0, $s3, $s1     # off = intsize*col
   add  $t0, $t0, $s4     # int *p = &rowp[col]
   lw   $t0, ($t0)        # t0 = *p
   add  $s0, $s0, $t0     # sum += t0
   addi $s3, $s3, 1       # col++
   j    loop2
end2:
   addi $s2, $s2, 1       # row++
   j    loop1
end1: