# i = 0, k = 1 and j = n/2 # while (k <= n*n) # if (i > -1 and j > -1 and j < n
ID: 3554442 • Letter: #
Question
# i = 0, k = 1 and j = n/2
# while (k <= n*n)
# if (i > -1 and j > -1 and j < n and i < n and a[i,j] == 0)
# a[i,j] = k
# i = i - 1, j = j +1 and k = k + 1
# else if (i < 0 and j == n) move out of upper right square
# i = 1 and j = n - 1
# else if (j == n) move out of right side of square
# j = 0
# else if (i < 0) move above top row
# i = n - 1
# else move to an already filled square
# i = i + 2 and j = j - 1
# end if - else
# end while loop
# Register usage
# $a0 = base address of array (matrix), a
# $a1 = n, size of matrix (number of rows and columns)
# $t0 = i
# $t1 = j
# $t2 = k
# $t3 = n*n
# $t4 = arraya index - in steps
# $t5 = array value
Explanation / Answer
#address of a in $t0 and a is a nXn matrix of words-> a(i,j) will be at address $t0+4(n*j+i)
# i = 0, k = 1 and j = n/2
li $t0,0
li $t2,1
move $t1,$a1
srl $t1,$t1,1
move $t3,$a1
mul $t3,$t3,$t3
# while (k <= n*n)
while:
# if (i > -1 and j > -1 and j < n and i < n and a[i,j] == 0)
ble $t0,-1,else #i<= -1 -> else
ble $t1,-1,else #j<= -1 -> else
bge $t1,$a1,else #j>=n -> else
bge $t0,$a1,else #i>=n -> else
#a(i,j) will be at address $t0+4(n*j+i)
mul $t4,$a1,$t1 #t4 = n*j
add $t4,$t4,$t0 #t4 = n*j + i
add $t4,$t4,$t4 # t4 = 2(n*j+i)
add $t4,$t4,$t4 # t4 = 4(n*j+i) multipy by 4 because the array is of wrods, each word is 4 bytes
add $t4,$a0,$t4 #now t4 has address of a(i,j)
lw $t5,0($t4)
bne $t5,0,else
sw $t2,0($t4) # a[i,j] = k
# i = i - 1, j = j +1 and k = k + 1
subi $t0,$t0,1# i = i - 1
addi $t1,$t1,1# j = j + 1
addi $t2,$t2,1# K = K + 1
# else if (i < 0 and j == n) move out of upper right square
# i = 1 and j = n - 1
check:
#(k <= n*n)
ble $t2,$t3,while
end:
#execution comes here after the end of while
b end
else:
# else if (i < 0 and j == n) move out of upper right square
bge $t0,0,else1 # i >= 0 -> out of else and go for checking the while condition
bne $t1,$a1,else1 # j != n -> out of else and go for checking the while condition
# i = 1 and j = n - 1
li $t0,1 # i = 1
subi $t1,$a1,1 # j = n - 1
b check
else1:
# else if (j == n) move out of right side of square
bne $t1,$a1,else2
# j = 0
li $t1,0
b check
else2:
# else if (i < 0) move above top row
bge $t0,0,else3
# i = n - 1
subi $t0,$a1,1
b check
else3:
# else move to an already filled square
# i = i + 2 and j = j - 1
addi $t0,$t0,2
subi $t1,$t1,1
b check
# end if - else
# end while loop
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.