Reputation: 1387
Let's say we have an array of 10 numbers and we want to sum those numbers to a variable like this:
int arr[10]= {1, 15, 0, -3, 99, 48, -17, -9, 20, 15};
sum = 0;
for(i=0; i<10; i++)
sum = sum + arr[i];
When I try to "assembly mips" this, a particular line goes off:
.data
arr: .word 1, 12, 0, -3, 99, 48, -17, -9, 20, 15
.text
.globl main
main:
add $t0, $zero, $zero #counter i
add $t1, $zero, $zero #sum
la $t2, arr #loading the address of the array to a register
loop:
slti $t3, $t0, 10 #i<10
beq $t3, $zero, EXIT
add $t1, $t1, $t2($t0) #wrong wrong very wrong
addi $t0, $t0, 1 #i++
j loop
EXIT:
li $v0, 10
syscall
I have a problem understanding how to express the "arr[i]" point to Assembly.
What is the right expression for it?
Do I have to take another registry for each number of the array?
Upvotes: 3
Views: 17037
Reputation: 1387
Thanks to Jester from above, the correct code for this is the following:
.data
arr: .word 1, 12, 0, -3, 99, 48, -17, -9, 20, 15
.text
.globl main
main:
add $t0, $zero, $zero #counter i
add $t1, $zero, $zero #sum
la $t2, arr
loop:
slti $t3, $t0, 10 #i<10
beq $t3, $zero, EXIT
lw $t4, ($t2) #$t4 = arr[i]
addi $t2, $t2, 4
add $t1, $t1, $t4 #sum = sum + arr[i]
addi $t0, $t0, 1 #i++
j loop
EXIT:
add $a0, $zero, $t1 #moving the sum to $a0 register for printing
li $v0, 1
syscall
li $v0, 10
syscall
Upvotes: 5