Wednesday, May 13, 2020

Sum and integer average of array elements in MIPS

This is a sample MIPS program that computes the sum and the integer average for the elements of an array of integers. The code is fully documented.

Launch EzMIPSthe MIPS assembler simulator, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.

# Compute the sum and integer average for the elements of an array #
# ---------------------------------------------------------------- #

# ---------------------- Data Declarations ----------------------- #

.data

array:       .word 21, 23, 25, 27, 29, 31, 33, 35, 37, 39
             .word 41, 43, 45, 47, 49, 51, 53, 55, 57, 90

array_size:  .word 20
sum:         .word 0
average:     .word 0

szSumIs:     .asciiz "The sum of 20 array elements is: "
szAverageIs: .asciiz "\nThe average 20 array elements is: "

# ---------------------------------------------------------------- #

# Basic approach:
# - loop through the array
# - access each value, update sum
# - calculate the average

.text

# ................................................................ #
main:
    lw $t2, array_size              # $t2 = array_size
    beq $t2, $zero, done            # if array size = 0, do not calulate anything!

    la $t0, array                   # $t0 = array starting address
    li $t1, 0                       # $t1 = loop index
    li $t3, 0                       # initialize sum, $t3 = 0

# Loop through the array to calculate sum
calc_sum:
    lw $t4, ($t0)                   # get array[i]
    add $t3, $t3, $t4               # sum = sum + array[i]

    addi $t1, $t1, 1                # i = i+1
    addi $t0, $t0, 4                # update array address (each word is 4 bytes)

    blt $t1, $t2, calc_sum          # if i<length, continue
    sw $t3, sum                     # save sum

# ...................... calculate average ....................... #

    div $t3, $t2                    # $lo = $t3/$t2 = sum/array_size
    mflo $t5                        # move integer average to $t5
    sw $t5, average                 # save average

done:
# ................................................................ #
    la $a0, szSumIs
    li $v0, 4
    syscall                         # print "The sum of 20 array elements is: "

    la $a0, sum
    lw $a0, 0($a0)
    li $v0, 1                       # print integer
    syscall                         # print it!

    la $a0, szAverageIs             # print "\nThe average 20 array elements is: "
    li $v0, 4
    syscall

    la $a0, average
    lw $a0, 0($a0)
    li $v0, 1                       # print integer
    syscall                         # print it!

    # Done, terminate program
    li $v0, 10                      # terminate
    syscall                         # system call

# ---------------------------------------------------------------- #

Please let me know of any suggestions or bugs regarding the code above.

Regards,

Antonis

No comments:

Post a Comment