Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following fragment of C code: for (i=0; i<=10; i++) { a[i] = b[i] +

ID: 3601026 • Letter: C

Question

Consider the following fragment of C code: for (i=0; i<=10; i++) { a[i] = b[i] + C; } Assume that a and b are arrays of words and the base address of a is in $a0 and the base address of b is in $a1. Register $t0 holds the variable i and register $s0 the constant C. Write the code for this fragment in MIPS

Would this be a valid answer? If it's incorrect can someone please explain why. Thank you

add $t0, $zero, 0               # initialize i = 0
ori $t4, $zero, 404               # initialize t4 to set number of bytes (101 * 4)

Loop:

add $t1, $a1, $t0               # $t1 = address of b[i]
lw $t2, 0($t1)               # $t2 = b[i]
add $t2, $t2, $s0               # $t2 = b[i] + c
add $t3, $a0, $t0               # $t3 = address of a[i]
sw $t2, 0($t3)           # a[i] = b[i] + c
addi $t0, $t0, 4               # i = i + 4
bne $t4, $zero, Loop       # goto Loop if i <= 404

Explanation / Answer

Translating from C to MIPS

=============================

for (i=0; i<=10; i=i+1)

{

a[i] = b[i] + c;

}

Assume that a and b are arrays of words and the base address of a is in $a0 and the base address of b is in $a1. Register $t0 holds the variable i and register $s0 the constant C.

(a) Write the code in MIPS TAL.

(i) one possible solution:

start: ori $t4, $zero, 404 # set number of bytes to loop

add $t0, $zero, zero # reset variable i

loop: addu $t1, $a0, $t0 # get address of a[i]

addu $t2, $a1, $t0 # get address of b[i]

lw $t2, 0($t2) # load b[i]

add $t2, $t2, $s0 # b[i] + c

sw $t2, 0($t1) # put sum in a[i]

addi $t0, $t0, 4 # advance i

bne $t0, $t4, loop # exit loop when we are greater

# than 10 elements

# (i.e. we reach 400+4 bytes)

(ii) another possible solution:

Start: add $t0, $zero, $zero # $t0 = 0

addi $t2, $zero, 4 # $t2 = 4

addi $t3, $zero, 401 # $t3 = 401

Loop: add $t4, $a1, $t0 # $t4 = address of b[i]

lw $t5, 0($t4) # $t5 = b[i]

add $t6, $t5, $s0 # $t6 = b[i] + c

add $t7, $a0, $t0 # $t7 = address of a[i]

sw $t6, 0($t7) # a[i] = b[i] + c

add $t0, $t0, $t2 # i = i + 4

slt $t8, $t0, $t3 # $t8 = 1 if $t0 < 401, i.e., i <=10

bne $t8, $zero, Loop # go to Loop if i <= 10

(b) How many TAL instructions are executed during the running of this code?

(i) We go 10 times through the loop. Number of instructions executed: 2+(7*11) = 79 TAL instructions.

(ii) 3+(8*11) = 91 TAL instructions.

(c) How many memory data transfer instructions (lw & sw) will be made during the running of this code?

(i and ii are the same) 2*11 = 22 memory data transfer instructions.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote