Wednesday, February 26, 2020

Store array index in all array locations, print

This sample MIPS source code will store the array index in all array locations [0..99] and print. Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS. Assemble, Run.


# --- store in every array location its array index --- #

.data

szarray: .asciiz "array["
szequal: .asciiz "] = "
szLF:    .asciiz "\n"

.text

# ----------------------------------------------------- #
main:
    
    add $t0, $zero, $zero  # t0 used as a counter (i = 0)
    move $t1, $gp          # t1 = the address of the first
                           # element ($gp = 0x10008000)
    addi $t2, $0, 100      # t2 = 100
    
# ----------------------------------------------------- #
start:
    
    slt $t3, $t0, $t2      # if ($to < $t2) -> $t3 = 1
                           # otherwise $t3 = 0 

    beq $t3, $zero, print   # is $t3 = 0 -> done!

    sw $t0, 0($t1)         # a[i] = i, ie a[0] = 0, a[1] = 1 ...
    addi $t0, $t0, 1       # i = i + 1
    addi $t1, $t1, 4       # next address = address + 4
                           # (this is array of words)
    j start                # continue

# ----------------------- Print ----------------------- #

print:

    add $t0, $zero, $zero  # t0 used as a counter (i = 0)
    move $t1, $gp          # t1 = the address of the first
                           # element ($gp = 0x10008000)
    addi $t2, $0, 100      # t2 = 100
    

# ..................................................... #
next:
    slt $t3, $t0, $t2      # if ($to < $t2) -> $t3 = 1
                           # otherwise $t3 = 0 
    beq $t3, $zero, done   # is $t3 = 0 -> done!

    # print "array["
    li $v0, 4
    la $a0, szarray
    syscall

    # print integer index
    li $v0, 1
    move $a0, $t0
    syscall

    # print "] = "
    li $v0, 4
    la $a0, szequal
    syscall

    # read value from memory and print
    li $v0, 1
    lw $a0, 0($t1)
    syscall

    # print newline
    li $v0, 4
    la $a0, szLF
    syscall
# ..................................................... #

    addi $t0, $t0, 1       # i = i + 1
    addi $t1, $t1, 4       # next address = address + 4
                           # (this is an array of words)
    j next

# --------------------- exit program ------------------ #
done:
    li $v0, 10
    syscall

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

Regards,

Antonis

No comments:

Post a Comment