Reputation: 103
I need to implement this code in the MARS emulator:
int x[10] = { /* initial values */ } ;
int i;
for(i=0; i<10; i++){
print i;
}
for (i=0; i<10; i++){
x[i] = 2*i+1;
print x[i];
}
Heres what I have:
.data
i: .word 0
x: .word 1,2,3,4,5,6,7,8,9,10
.align 2
.text
.globl main
main:
lw $t0, i
lw $t1, x
li $t4, 4
jal L0
li $t0, 0
jal L1
li $v0, 10 # terminate
syscall
L0:
li $v0, 1
la $a0, ($t0)
syscall
addi $t0, $t0, 1
bge $t0,10, RETURN #goto L1 if NOT n<0
b L0
L1:
li $v0, 1
la $a0, ($t1)
syscall
mul $t2, $t0, $t4
lw $t1, x + ($t2) #########this line#########
addi $t0, $t0, 1
bge $t0,10, RETURN
b L1
RETURN:
jr $ra
I commented next to the line that I believe to be the source of my problem. That is essentially the line that is referencing x[i]. I multiplied i by 4 and added that value to x, in attempt to reference the appropriate word in the array. I don't know how to properly implement this concept.
Thanks for the help.
Upvotes: 0
Views: 145
Reputation: 58427
You need to do something like this:
L1:
la $a1,x # $a1 = &x
L2: # do {
addu $a0,$t0,$t0 # $a0 = i*2
addiu $a0,$a0,1 # $a0 = i*2 + 1
sw $a0,($a1) # x[i] = i*2 + 1
addiu $a1,$a1,4 # a1 = &x[i+1]
li $v0,1 # print_int
syscall # print_int(i*2 + 1)
addiu $t0,$t0,1 # i++
bne $t0,10,L2 # } while (i != 10)
jr $ra
And stuff like la $a0, ($t0)
looks really weird. Please use the much clearer move $a0, $t0
instead.
Upvotes: 1