user677786
user677786

Reputation: 475

MIPS ASM Homework - Arrays and while loops

First, let me say this...I don't want anyone to just give me an answer...I'd like to be pointed in the right direction!

I have an array of integers in this program....for instance:

numbers:
     .word  17
     .word -50
     .word   1
     .word -999

I have a while loop that runs through them and prints each one on a new line. That works fine. (-999 is the terminating number, and is not included in the printout)

I also need to print them in the reverse order. I know that I could use a loop to count the number of elements and then have another loop that starts at the last address and goes backwards....this seems to be inefficient, though.

Is there some way to find the address of the last element in an array without doing a loop first? If not, I can do it this way I mentioned, just want to make sure I'm being as efficient as I can in the program.

Thanks in advance!

Upvotes: 0

Views: 506

Answers (1)

Richard Pennington
Richard Pennington

Reputation: 19965

If you are allowed to do any assembly tricks you want, you could do something like

numbers:
 .word  17
 .word -50
 .word   1
last:
 .word -999

and use code like this pseudo code

for (ptr = last; ptr != numbers; ) print(*--ptr);

In other words, put a label and the end of the array and walk backwards until you hit the beginning of the array, using a pointer comparison instead of looking for the terminator (-999).

Or, to avoid changing you code too much, how about

 .word -999
numbers:
 .word  17
 .word -50
 .word   1
last:
 .word -999

and walk backward until you find the -999?

Upvotes: 1

Related Questions