1

For example,

$a0 is an index/pointer
$a1 is the address of the array base

I want to access each element of the array within a loop, perform an arithmetic operation to that element, then save it to the next. The index should increase +1 on each iteration.

For a simple example, I'm trying to square each previous element in the array. Initial hard coded values are INDEX[0]=0, ARRAY[0]=2. I've marked where I'm confused. I don't know how to make this variable for each loop.

       .data
INDEX: .space  4
       .align  2
ARRAY: .space  16
       .align  2

       .text
        la     $a0, INDEX
        la     $a1, ARRAY
        li     $t0, 0
        sw     $t0, ($a0)       # set INDEX[0]=0
        li     $t0, 2
        sw     $t0, ($a1)       # set ARRAY[0]=2

LOOP:
        lw     $t0, ($a0)
        sll    $t0, $t0, 2      # $a0 * 4 to get element offset
        lw     $t1, $t0($a1)    # STUCK HERE (1)
        add    $t1, $t1, $t1    # square
        lw     $t0, ($a0)
        add    $t0, $t0, 1
        sw     $t1, $t0($a1)    # AND HERE (2)
        add    $a0, $a0, 1

               ... keep looping if space remaining in $a1

(1) How do I save the element ARRAY[INDEX] to register $t1 without hardcoding the offset?

(2) How do I save the altered register $t1 to a specific element in the array: ARRAY[INDEX] = $t1

Since the indirect addressing will change on each loop, I want to avoid using 4($a1), 8($a1), etc.

Thank you.

1 Answer 1

1

You need to add the base address and index together. Something like this ought to work:

    sll    $t2, $t0, 2      # $a0 * 4 to get element offset
    add    $t2, $t2, $a1    # Add the array base address to the scaled index
    lw     $t1, ($t2)       # $t1 = ARRAY[index]
    add    $t1, $t1, $t1    # square
    add    $t0, $t0, 1
    sw     $t1, ($t2)       

Note that you're not actually squaring numbers - you're doubling them (t1 = t1 + t1). To square a number you'd multiply it by itself.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the solution. I will let you know how it goes when I complete this. I'm actually doing fibonacci instead of squaring, so this will take me a little longer to figure out.
I'm getting an address out of range error when I load one of my registers with ARRAY[INDEX], but it could definitely be something else in my code. I will continue to troubleshoot it. The line that's causing the error is: lw $t1, ($t2)
Use a debugger to check the index and make sure you exit the loop when the index reaches the size of the array divided by the size of each element.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.