Reputation: 5
I need help with this last part of this problem. I'm basically trying to translate C++ code into MIPS Assembly language.
Assume a is in $s0, b in $s1, c in $s2, x in $s4, y in $s5, and z in $s6.
I finished almost all of them but I am stuck on these two, I know some parts of it but I'm having trouble putting it together as a whole. The parts I know will be followed by hashtags with the assembly code. Thanks for any help.
1.
for(x = 0; x <= z; x++) # x = 0; is: addi $s4, $0, 0
y = y + 1; # addi $s5, $s5, 1
y = 0; # addi $s5, $0, 0
2.
if(y > z)
x = 0; # addi $s4, $0, 0
else x = 1; # else: addi $s4, $0, 1
Here are the oringinal problems without the hashtags incase I am wrong:
1.
for(x = 0; x <= z; x++)
y = y + 1;
y = 0;
2.
if(y > z)
x = 0;
else x = 1;
Thanks again.
Attempt at 2, not sure if right.
ifLoop:
add $s5, ? , $s6
addi $s4, $0, 0
ifLoop
else:
addi $s4, $0, 1
else
Practice: (Assume array p is in $s7)
p[0] = 0;
int a = 2;
p[1] = a;
p[a] = a;
My attempt:
sw $0, 0($s7)
addiu $s0, $0, 2
sw $s0, 4($s7)
sll $t0, $s0, 2
addu $t1, $t0, $s7
sw $s0, 0($t1)
Upvotes: 1
Views: 5112
Reputation: 1270
Edit: 1. Luckily it is not much different without pseudo instructions.
addi $s4, $0, 0
forLoop: sle $t1, $s4, $s6 #if x <= z, set $t1 to 1, else 0
addi $s5, $s5, 1
addi $s5, $0, 0
addi $s4, $s4 1
bne $t1, $0, forLoop #repeat loop while $t1 is not 0
Here is #2. I just wanted for you to give it a go before I just gave the answer. You want to use the slt instruction to set a register to 1 or 0. If 1, the comparison is true (y > z). Then use bne to determine where to jump to. By comparing the bne to 0, the true code ends up being directly below the bne instruction. For the else, jump to the label.
slt $t2, $s6, $s5 # if z < y, set $t2 to 1, else 0
bne $t2, $0, else # if $t2==1, do the code below, if not, go to else
addi $s4, $0, 0
j continue # need the jump instruction to skip the else below
else:
addi $s4, $0, 1
continue:
# rest of code/program
Upvotes: 1