I want to loop through an array of numbers like
.word 2,2,2,2,2,2,2,2,2,2,2,2,2
.word 2,2,2,2,2,2,2,2,2,2,2,2开发者_JAVA百科,2
.word 2,2,2,2,2,2,2,2,2,2,2,2,2
.word 2,2,2,2,2,2,2,2,2,2,2,2,2
and I want to make sure that everything in the array is value 2. Now these are 52 elements so every time I want to check whether all the array elements are 2..other wise do something else.
That's what I've done so far:
add $t6,$0,$0
add $t7,$0,$0
SL:
addi $t6,$t6,4
addi $t7,$t7,1
la $t1,array
add $t1,$t1,$t6
lw $s0,($t1)
j check
slti $t8,$t7,52
bnez $t8,SL
jr $ra
check:
li $t3,2
seq $t4,$s0,$t3
beqz $t4,do_something
bnez $t4,exit
jr $ra
But when I make an array like this
.word 0,2,2,2,2,2,2,0,2,2,2,2,2
.word 2,2,2,2,2,2,2,2,2,2,2,2,
.word 2,2,2,2,2,2,2,0,2,2,2,2,2
.word 2,2,2,2,2,2,2,2,2,2,2,2,0
it still exits even though the array is not all 2s.
To do this, you'd want to start by accessing the first element of each array, and then loop until your pointer (or memory address) is outside of the range of the array. The address of the array is also the address of the first element (and has an offset of 0 bits), and the last element has an offset of 48 bits.
Let $t0 be the address of the current element, and $t1 be out of bounds.
la $t0, array
addiu $t1, $t0, 52 # 52 is outside the array
L1:
beq $t0, t1, L2
# do something here
addiu $t0, $t0, 4
j L1
L2:
# this part of the code happens after you traverse through an array.
Also, you can use addi instead of addiu, but as you will probably learn later in the course, addi can cause an exception.
精彩评论