In: Computer Science
2. Translate the following C/Java code to MIPS assembly code. Assume that the values of a, i, and j are in registers $s0, $t0, and $t1, respectively. Assume that register $s2 holds the base address of the array A (add comments to your MIPS code). j = 0;
for(i=0 ; i<a ; i++)
A[i]=i+j++;
C Code:-
for (i=0;i<a; i++)
A[i] = i + j++;
MIPS Code:-
# s0 --> a
# t0 --> i
# t1 --> j
# s2 --> base address of array A, i.e. A[0]
# s3 --> A[i]
#START
li $t0,0 #load immediate $t0 with 0 We are assigning i=0
li $t1,0 #load immediate $t1 with 0 We are assigning j=0
loop: #for (i=0;i<a; i++)
bgt $t0, $s0, end # if $t0 > $s0, means if i>a then the loop moves to end.
lw $s3, 4($s2) # here we load the contents of the word in to address of $s2. 4 is an offset here.
addi $t1, $t1, 1 # j++
addi $s3, $t0, $t1 # A[i] = i + j++
addi $s2, $s2, 4 # next element A[i+1]
addi $t0, $t0, 1 # add 1 to $t0
j loop # jump back to the top
end:
syscall # End program