Consider the following fragment of C code: for (i=0; i<=100; i++) { a[i] = b[i]
ID: 3600722 • Letter: C
Question
Consider the following fragment of C code:
for (i=0; i<=100; 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. How many total instructions are executed during the running of your code? How many memory data references will be made during execution? Typing your answer is recommended.
Add comments to each line of the following MIPS code. Then, describe what it computes (one or two sentences). Assume that $a0 is used for the input and initially contains n, a positive integer. Assume that $v0 is used for returning the output value.
begin: addi $t0, $zero, 0
addi $t1, $zero, 1
loop: slt $t2, $a0, $t1
bne $t2, $zero, finish
add $t0, $t0, $t1
addi $t1, $t1, 2
j loop
finish: add $v0, $t0, $zero
Explanation / Answer
MIPS CODE FOR LOOP SEGMENT
addi $t6, $zero, 101 # the loop termination value
add $t0, $zero, $zero # i = 0
addi $t2, $a0, 0 # ptr to current A[i]
addi $t3, $a1, 0 # ptr to current B[i]
loop: lw $t4, 0($t3) # load B[i]
add $t4, $t4, $s0 # B[i] + c
sw $t4, 0($t2) # store in A[i]
addi $t0, $t0, 1 # i++
addi $t2, $t2, 4 # ptr to next A[i]
addi $t3, $t3, 4 # ptr to next B[i]
bne $t0, $t6, loop # if i < 101, goto loop
The loop is executed 101 times and the loop contains 7 statements. There are 4 statements outside the loop. Therefore, the total number of instructions executed is 4 + (7*101) = 711.
The total number of memory data reference: 101 * 2 = 202.
Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.