# grid.s -- Initialize and print out a 2-D array # This program illustrates how to implement 2-D row-major addressing. # Take a look at the calculations performed in the inner loop. # The output of this program will look like this # 31415 # 92653 # 58979 # 32384 # 62643 .data array: .word 3, 1, 4, 1, 5 # Here we initialize 25 elements of the array. .word 9, 2, 6, 5, 3 # To the machine, all arrays are 1-D -- .word 5, 8, 9, 7, 9 # It's only how we use the array that makes .word 3, 2, 3, 8, 4 # it 2-D. .word 6, 2, 6, 4, 3 nl: .asciiz "\n" # $s0 = base address of the array # $s1 = number of rows # $s2 = number of columns # $s3 = row number # $s4 = col number # $s5 = offset # $s6 = total address # $s7 = number obtained from the array .text main: la $s0, array # set the base address li $s1, 5 # initialize number of rows and cols li $s2, 5 li $s3, 0 # initialize row number to 0 outer: li $s4, 0 # initialize col number to 0 inner: # Compute offset in 3 instructions... mul $s5, $s3, $s2 # multiply i * num_cols add $s5, $s5, $s4 # add col number mul $s5, $s5, 4 # multiply by 4 (size of int) add $s6, $s0, $s5 # total = base + offset lw $s7, 0($s6) # load value from array li $v0, 1 # print this integer move $a0, $s7 syscall addi $s4, $s4, 1 # increment col number blt $s4, $s2, inner # continue with next cell in this row li $v0, 4 # print newline la $a0, nl syscall addi $s3, $s3, 1 # increment row number blt, $s3, $s1, outer # continue with next row li $v0, 10 # end of program syscall