Exercise Chap4
Exercise Chap4
MARS intro
Hello World
.text #Code segment to store instructions
addi $t1,$zero,2 #$t1 = 2
addi $t2,$zero,3 #$t2 = 3
add $t0, $t1, $t2 #$t0 = $t1 + $t2
Ex.1
• Implement the following pseudo program in MIPS
assembly.
• Assume that x, y, z, i, j are in s1, s2, s3, t0, t1.
if (i<=j){
x=x+1;
z=1;
}
else {
y=y-1;
z=2*z;
}
Solution
start:
slt $t0,$s2,$s1 # j<i
bne $t0,$zero,else # branch to else if j<i
addi $t1,$t1,1 # then part: x=x+1
addi $t3,$zero,1 # z=1
j endif # skip “else” part
else: addi $t2,$t2,-1 # begin else part: y=y-1
add $t3,$t3,$t3 # z=2*z
endif:
Ex.2
Find the sum of all elements in array A
loop: i = i + step;
sum=sum + A[i];
if (i != n) goto loop;
Solution
.text
loop:
add $s1,$s1,$s4 #i=i+step
add $t1,$s1,$s1 #t1=2*s1
add $t1,$t1,$t1 #t1=4*s1
add $t1,$t1,$s2 #t1 store the address of A[i]
lw $t0,0($t1) #load value of A[i] in $t0
add $s5,$s5,$t0 #sum=sum+A[i]
bne $s1,$s3,loop #if i != n, goto loop