如何使用循环在Assembly中查找数组的最小值和最大值?

时间:2019-10-24 01:17:50

标签: arrays assembly max mips qtspim

我正在尝试在Assembly中查找并打印数组的最小值和最大值。我现在的主要问题是增加数组索引的值。将文件加载到QTSpim时,我不断收到语法错误。我敢肯定还有很多问题,但是我稍后再讨论。

我的问题是为什么我不能将数组增加到下一个值?语法错误是什么?

这是我的代码:

        .data

    array:      .word   5, 7, 12, 3, 4, 9, 6, 11, 2, 10
    array_size: .word   10
    array_min:  .asciiz "\nMin: " 
    array_max:  .asciiz "\nMax: "



    .text
    .globl main

main:   

    la $a1, array       # loading memory address of array

    addi $t0, $zero, 0  # setting index incrementer to 0
    lw $s1, 0($a1)      # setting $s1 to the smallest index of the array
    lw $s2, 0($a1)      # setting $s2 to the smallest index of the array

while:

    beq $t0, 10, exit   # branch to exit if $t0 is 10
    addi $t1, $t1, 4    # too add the next four bytes for the array index

    blt array($t1), $s1, minimum    # branch to minimum if $array[$t1] < $s1 
    blt array($t1), $s2, maximum    # branch to maximum if $array[$t1] < $s2

    minimum:
        lw $s1, array($t1)
        j while
    maximum:
        lw $s2, array($t1)
        j while



    addi $t0, $t0, 1    # increment $t0 by 1

    j while             # jump to the beginning of the while loop

exit:   

    li $v0, 4           # prints the array_min string
    la $a0, array_min
    syscall

    li $v0, 1           # prints the smallest integer
    move $a0, $s1
    syscall

    li $v0, 4           # prints the array_max string
    la $a0, array_max
    syscall

    li $v0, 1           # prints the largest integer
    move $a0, $s2
    syscall


    li $v0, 10          # terminates program
    syscall

谢谢!

1 个答案:

答案 0 :(得分:0)

对于它的价值,这里是可以执行此操作的MIPS代码。

.data

array:      .word   5, 7, 12, 3, 4, 9, 6, 11, 2, 10
array_size: .word   10
array_min:  .asciiz "\nMin: " 
array_max:  .asciiz "\nMax: "

.text

main:   
    la $a0, array
    lw $a1, array_size
    lw $t2, ($a0) # max
    lw $t3, ($a0) # min
    loop_array:
        beq $a1, $zero, print_and_exit
        lw $t0, ($a0)
        bge $t0, $t3, not_min # if (current_element >= current_min) {don't modify min} 
        move $t3, $t0
        not_min:
        ble $t0, $t2, not_max # if (current_element <= current_max) {don't modify max}
        move $t2, $t0
        not_max:
        addi $a1, $a1, -1
        addi $a0, $a0, 4
        j loop_array

    print_and_exit:
    # print maximum
    li $v0, 4
    la $a0, array_max
    syscall

    li $v0, 1
    move $a0, $t2
    syscall 

    # print minimum
    li $v0, 4
    la $a0, array_min
    syscall

    li $v0, 1
    move $a0, $t3
    syscall 

    # exit
    li $v0, 10
    syscall