0

Here is the code to find the sum of positive number and negative number. However, the code have arithmetic overflow when running (runtime exception at 0x00400034). The basic idea is to use the for loop but the error occured. Did I miss any element for doing the for loop?

  .data

    array: .word -13, 82, 56, 63, -54
    length: .word 10
    newLine: .ascii "\n"
    posSumMsg: .ascii "Positive value = "
    negSumMsg: .ascii "Negative value = "
    posSum: .word 0
    negSum: .word 0

.text
.globl main
main:
    la $t0, array #the starting address of the array
    li $t1, 0 # set the loop index, where i = 0
    lw $t2, length # length
    li $t3, 0 # initialize the sum to be 0 for pos_sum
    li $t5, 0 # initialize for neg_sum

    #start of loop
sumLoop:
    lw $t4, ($t0) #get the array[i]
    blt $t4, 0, getNegSum #jump to the negative sum calculation block for negative number
    bgt $t4,0, getPosSum #jump to positive sum calculation block for positive number

    #calcuates the sum for positive numbers
getPosSum:
    add $t3, $t3, $t4 #sum = sum + array[i]
    j loopback

getNegSum:
    add $t5, $t5, $t4

    #loopback of the array
loopback:
    add $t1, $t1, 1 #i = i+1
    add $t0, $t0, 4 # update the address of the array
    bnez $t4, sumLoop # stop the for loop if the last elemnt is a 0, otherwise loop back

    #store the sum
    sw $t3, posSum 
    sw $t5, negSum

    #print a message
    li $v0, 4
    la $a0, posSumMsg
    syscall

    #print value
    li $v0, 1
    move $a0, $t3 
    syscall

    #print a message
    li $v0, 4
    la $a0, negSumMsg
    syscall

    #print a value
    li $v0, 1
    move $a0, $t5
    syscall

    #Terminate the program
    li $v0, 10
    syscall
.end main
  • 1
    See my answer here: https://stackoverflow.com/a/39479000/5382650 – Craig Estey Mar 01 '20 at 18:08
  • 1
    Unlike that one, this code is using a zero word terminator to decide when to exit the loop processing the array elements. However, the data doesn't have this terminator, so will continue to sum the past the end of the array, adding up the string literals that come after. – Erik Eidt Mar 01 '20 at 19:02

0 Answers0