使用while循环遍历数组?-MIPS [英] looping through array using while loop? - MIPS

查看:56
本文介绍了使用while循环遍历数组?-MIPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历像这样的数字数组

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,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

,我想确保数组中的所有值均为2.现在这些是52个元素,因此每次我要检查是否所有的数组元素都为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

即使数组不是全为2,它仍然会退出.

it still exits even though the array is not all 2s.

推荐答案

为此,您需要先访问每个数组的第一个元素,然后循环直到指针(或内存地址)不在数组的范围.数组的地址也是第一个元素的地址(偏移量为0位),最后一个元素的偏移量为48位.

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.

让$ t0为当前元素的地址,而$ t1为越界.

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.

此外,您可以使用addi代替addiu,但是您可能会在本课程的后面学到​​,所以addi可能会导致异常.

Also, you can use addi instead of addiu, but as you will probably learn later in the course, addi can cause an exception.

这篇关于使用while循环遍历数组?-MIPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆