Monday, May 18, 2020

MIPS sum of the array elements

This is another sample MIPS program that computes the sum of all array elements. The code is fully documented.

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

#-------------- Find the sum of the array elements ----------------#

# --------------------------- data ------------------------------- #
.data

elements: .word 12                               # nuber of array elements
array:    .word 3,   4,  7, 10, 15, 21           # array of numbers
          .word 23, 34, 67, 88, 99, 100

sum:      .word 0
szSumIs:  .asciiz "The sum of the array elements is = "
szLF:     .asciiz "\n"

#---------------------------- program -----------------------------#

.text

main:
    
    lw $s0, elements             # $s0 = nuber of array elements
    la $t0, array                # load the address of the array into $t0
    and $s1, $s1, $zero          # clear $s1 (keeps the running sum)

    # ........................ addition ...........................#
add_next:
    lw $t1, 0($t0)               # load the next value of the array
    add $s1, $s1, $t1            # add it to the running sum
    addi $t0, $t0, 4             # increment to the next address
    addi $s0, $s0, -1            # decrement the loop counter
    bne $0, $s0, add_next        # loop back until complete
    
    sw $s1, sum                  # store the final total

    # ....................... printing ............................#

    la $a0, szSumIs              # load address of szSumIs
    li $v0, 4                    # print string code
    syscall                      # print it!
    
    move $a0, $s1                # sum is kept in $s1, copy it to $a0
    li $v0, 1                    # print integer code
    syscall                      # print it!

    la $a0, szLF                 # load address of szLF
    li $v0, 4                    # print string code
    syscall                      # print it!

    # ..................... Exit program ..........................#

    li $v0, 10                   # syscall to exit cleanly
    syscall                      # Do it!

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

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

Regards,

Antonis

No comments:

Post a Comment