teddywestside
teddywestside

Reputation: 37

Using MIPS to find sum of array

So Im having trouble with a problem. Im givin that a is an array of words and the base address of a is saved in $a0. So for int a[10] find the sum of this array using mips. I really don't know where to start can someone help me start and I think I should be able to finish it. Thanks a bunch!

Upvotes: 0

Views: 6829

Answers (1)

Wiz
Wiz

Reputation: 2143

Since you are given the address of the start of the array, you know that is also your first element. Since this is an array of int, I will assume it means it will use a storage space the size of a word on mips32 which is 4 bytes. Therefore a[1] is located at the address of a[0]+4bytes. A[2] is located at the address of a[0]+8bytes or a[1]+4bytes etc...

From that it follows that all you have to do is just loop 10 times, loading a word each time and adding the value.

The basic flow is:

  1. Let count = 0, sum = 0 (sum is your return value, so $v0)
  2. Load a word value from $a0 into a register
  3. Set $a0 = $a0 + 4 (move from a[count] to a[count+1], integer is 4 bytes on mips32)
  4. Set sum = sum + the register you loaded the word value into
  5. count = count + 1
  6. if count < 10? (set less than, branch) go to #2
  7. jump and link (assuming our sum is already in $v0)

Note: The base address you are given MUST be word-aligned.

Optimization note: You can optimize the number of instructions executed by setting some register to $a0 + 40 before step 1. This means you can get rid of step 5 and step 6 will be a check if $a0 is less than that register you set before step 1. (The last optimization is moving step 4 to step 6's delay slot. If you are using a simulator, this might not be supported though)

Upvotes: 2

Related Questions