0
votes

Question. Write MIPS assembley code which is equivalent to the following Java code fragment.

    int x = 1 ;
    int y = 3 ;
    int c = 2 ;
    x = y - c ;
    if (x != y) { x = y + 5 ; }
    else { x = c ; } ;

This is what I have at the moment.

.data 
X: .word 1
Y: .word 3
C: .word 2
.text
main:
la $t1, X 
la $t2, Y
la $t3, C
lw $t1, ($t1)
lw $t2, ($t2)
lw $t3, ($t3)
sub $t1, $t2, $t3
li $v0, 1
beq $t1, $t2, iflabel
add $t1,$t3, 0 # sets x = c by adding zero to c and putting result in $t1 (register for x) used.
iflabel: add $t1,$t2,5
syscall
li $v0, 10

As Far as I can tell '8' should be printed, but instead 0 is ?!?, not a homework question, just some revision question on MIPS. I can guess that my syscall 's are probably in the wrong places and possibly causing the error maybe?, I'm using MARS to program in, as I can see the contents of the register and run each line one by one, but still doesn't help my problem.

2

2 Answers

1
votes

Your conditions are backwards: right now you have it so that is X is equal to Y it'll add 5, but from the Java code it looks like you want it the other way around:

bne $t1, $t2, iflabel

Secondly, your +5 code flows into the other condition. You need a label after the if/else block, and you need to branch to it after handling the if-true code.

Thirdly, you should be loading the $v0 vector immediately before doing syscall, and there's no reason to be doing it afterward.

Fourthly, syscall 1 needs the integer to be in $a0. You can directly add Y+5 or C+0 into $a0.

Final code should be:

.data 
X: .word 1
Y: .word 3
C: .word 2

.text
main:
la $t1, X 
la $t2, Y
la $t3, C
lw $t1, ($t1)
lw $t2, ($t2)
lw $t3, ($t3)
sub $t1, $t2, $t3
bne $t1, $t2, iflabel
add $a0,$t3, 0
b endif
iflabel: add $a0,$t2,5
endif:
li $v0, 1
syscall
0
votes

Is your integer in the right register? Seems from here that it should be in $a0