I am trying to get an average of ten numbers entered into an array. I am getting an an arithmetic overflow at add $a2, $a2, $a1
.
Not sure what I am doing wrong. Help would be appreciated.
Also, I tried switching the limit to 2 integers just because it would not overflow so quickly. It is adding the addresses together, instead of the integers. This is my guess as to why it keeps overflowing. How would I change the addresses to the integers, though?
Here is my code.
.data
nums:
.word 0,0,0,0,0,0,0,0,0,0
prompt:
.asciiz "Please enter 10 positive integers:\n"
avg:
.asciiz "Avg = "
result:
.asciiz " "
.text
.globl main
main:
li $v0, 4
la $a0, prompt
syscall
li $t1, 10
la $a1, nums
getnums:
addi $t1, $t1, -1
li $v0, 5
syscall
sw $v0, ($a1)
addi $a1, $a1, 4
bnez $t1, getnums
#avg
move $a2, $zero
move $t0, $zero
addi $a1, $a1, -4
getavg:
lw $t0, 0($a1)
addi $t1, $t1, 1
add $a2, $a2, $t0 #arithmetic overflow
addi $a1, $a1, -4
bne $t1, 10, getavg
li $v0, 4
la $a0, avg
div $a2, $a2, 10
syscall
la $a0, ($a2)
li $v0, 1
syscall
li $v0, 10
syscall
(Edited to fix code formatting - RobertB)
It looks like you're using $a1
as a pointer to the current word in memory. But when you do add $a2, $a2, $a1
, you're adding the contents of the register $a1
, not the contents of the memory address it points to. It won't take many cycles of adding a 32-bit memory address value to itself, before you hit an overflow.
The missing link is the Load Word instruction that would get the contents of the memory location:
lw $t0, 0($a1)
That would load the contents of the memory location pointed to by $a1
, into $t0
.