Andrew L
Andrew L

Reputation: 13

Array in Mips Assembly with looping

I am having an issue with my code. I am creating a program that will read in a string, save it into an array and then output the number of times each letter is used in the string. For right now I am having an issue with just the output of the string back to the screen. The string is outputted but the loop never exits, the $t2 value is maybe never set to a value?

.data
intro: .asciiz "Andrew Lofgren, Letter Checker Program" 
question: .asciiz "\nPlease enter a string for evaluation: "
alphabet: .ascii "ABCDEFGHIJKLMONOPQRSTUVWXYZ"
results: .space 104
string: .space 1024

.text 

main:
jal setup
jal analyze
#jal results

li  $v0, 10
syscall 

setup:
li  $v0, 4  # outputing name and program information
la  $a0, intro
syscall

li  $v0, 4  # asksing for string input
la  $a0, question
syscall 

li  $v0, 8
la  $a0, string
li  $a1, 1024
syscall

jr  $ra     # return

analyze: 
la  $t0, string # taking string and saving into a tmp
move    $t2, $t0    # backup of orignal address
find:   
beq $t1, 0, print
addi    $t0, $t0, 1
j find

print:  
blt $t0, $t2, end   #PROBLEM HERE
li  $v0, 11
lb  $a0, 0($t0)
syscall
addi    $t0, $t0, 1
j print
end:
jr  $ra

Upvotes: 0

Views: 1258

Answers (1)

user2128970
user2128970

Reputation:

$t0 will never be less than $t2, because $t0 continually increases while $t2 remains the same. To solve this, you need a third register, say $t7, which stores the final index of your string. To calculate the last index, simply add the base address of the string to length which you have defined as 1024. Once $t0 is no longer less than 1024 + string, there are no chars left in the string, and thus we branch to end:. This is done and explained further in the code segment below.

print:
    li      $t7 , 1024            # Load total byte length of the string
    add     $t7 , $t7 , $t2     # add it to the base address to get the end
    slt     $t6 , $t0 , $t7     # check to see if cur index < end
    beq     $t6 , $0 , end     # if we hit the end, branch to end

...

For more information on MIPS instructions, visit this page.

Upvotes: 1

Related Questions