You are on page 1of 1

CS232 Discussion 1: Solutions

1. do-while loops
Translate the following snippet of C code into MIPS:

i = 0; li $t0, 0 # t0 = i = 0
do { loop:
// stuff # stuff
i++; addi $t0, $t0, 1
} while(i < 4); blt $t0, 4, loop

2. while-style or do-while-style?
In the following snippet of C code, the value of variable n is unknown at compile-time. In order to
minimize the number of instructions executed at run-time, should a C-to-MIPS compiler translate
the loop using a while-style or a do-while-style loop?

for(i = 0; i < n; ++i) {


// stuff
}

Solution: Since do-while loops require less loop overhead in MIPS, it seems reasonable to think
that the compiler would prefer this style. However the compiler’s first concern is always correctness,
and it could be that the loop is never executed (i.e., n <= 0), in which case the do-while translation
is incorrect. A compiler must always err on the side of caution, which in this case could be a while-
style translation. With a test for n <= 0 before the loop, however, a smart compiler could use the
do-while-style after all.

3. Loop through an array


Translate this code into MIPS:

int sum = 0;
for(int i = 0; i < n; ++i)
sum += A[i];

Solution: We give two slightly different solutions below:

# a0 = &A[0], a1 = n # a0 = &A[0], a1 = n
li $t0, 0 # t0 = sum li $t0, 0 # t0 = sum
li $t1, 0 # t1 = i add $t1, $a0, $a1 # t1 = &A[n]
loop: loop:
bge $t1, $a1, done # is i >= n? beq $a0, $t1, done # reached end?
add $t2, $a0, $t1 # t2 = &A[i] lb $t2, 0($a0) # read byte
lb $t2, 0($t2) # t2 = A[i] add $t0, $t0, $t2 # sum += t2
add $t0, $t0, $t2 # sum += t2 addi $a0, $a0, 1 # advance pointer
addi $t1, $t1, 1 # i++ j loop
j loop done:
done:

You might also like