[prev] 8 [next]

1-d Arrays in MIPS (cont)

Scanning across an array of N elements using index

# int vec[10] = {...};
# int i;
# for (i = 0; i < 10; i++)
#    printf("%d\n", vec[i]);

   li   $s0, 0               # i = 0
   li   $s1, 10              # no of elements
   li   $s2, 4               # sizeof each element
loop: 
   bge  $s0, $s1, end_loop   # if (i >= 10) break
   mul  $t0, $s0, $s2        # index -> byte offset
   lw   $a0, vec($t0)        # a0 = vec[i]
   jal  print                # print a0
   addi $s0, $s0, 1          # i++
   j    loop
end_loop:

Assumes the existence of a print() function to do printf("%d\n",x)