Brian Daneshgar
Brian Daneshgar

Reputation: 343

Find max word in an array (MIPS Assembly)

I am trying to find the max word in an array using assembly. I have written the following but seems my loop is always branching. Any help is appreciated!

Solution is in the comments, thank you Jester

# find max from array
#
.data
array:  .word   3, 4, 7, 6, 5
max:    .word   0
.text
#
# -- register assignments  --
# $2 = counter
# $3 = sum
# $6 = loop limit (20)
#
# counter = 0
    and $2, $0, $0
# sum = 0
    and $3, $0, $0
    addi    $6, $0, 20
loop:
# if array[i] < max save array[i] as max
    lw  $4, array($2)
    ble     $3, $4, incrementCount
    move    $3, $4
incrementCount:
# counter++
# (words are 4 bytes, so advance counter by 4)
    addi    $2, $2, 4
# if counter < 5, loop (really < 20)
    blt $2, $6, loop
done:   sw  $3, max

Upvotes: 1

Views: 995

Answers (1)

Michael
Michael

Reputation: 58467

The operand order for your ble is incorrect. You're initially setting $3 = 0, and then you do ble $3, $4, incrementCount, i.e. if (0 <= element_just_loaded) goto incrementCount. This condition will always be true, since all the elements in your array are greater than 0, and the value of $3 will keep being 0 since the only time you change it is if the branch isn't taken.

The solution would be to switch the operands around so that you do ble $4, $3, incrementCount, i.e. if (element_just_loaded <= current_max) goto incrementCount.

Upvotes: 1

Related Questions