storing array from user and accessing it

82 views Asked by At

I have to create an int array based on user input, sum the integers, and output the sum and the array itself.

My code calculates the sum correctly, but I cannot output the list. It only prints out the last number and zeros and then gets stuck in an infinite loop in PRINTLIST.

I think the problem is accessing the array. Can anyone help me?

    .data   

intro:  

    .asciiz "Enter numbers\n"

sum:    

    .asciiz "\nSum= "

list:

    .asciiz "\nList looks like: "       

array:  

    .space 400
    .text

main:

    li  $t1,0       #count
    la  $a1,array   

    li  $v0,4
    la  $a0,intro   
    syscall

    j   INPUT
    jr  $ra

GETLIST:

    li   $v0, 5     
    syscall

    move $t0,$v0    
    bltz $t0,SUM    #leave if negative

    add $t2,$t2,$t0 
    add $t1,$t1,1   #increment counter

    sw  $v0,0($a2)  #store in array
    add $a0,$a0,4   

    move $t5,$t2    

    j   GETLIST     

SUM:

    li  $v0,4
    la  $a0,sum
    syscall

    li  $v0,1
    move    $a0,$t5     #sum to a0
    syscall

    li  $v0,4
    la  $a0,list
    syscall

    add $t1,$t1,-1
PRINTLIST:

    lw  $t0,0($a1)
    add $a1,$a1,4
    add $t1,$t1,-1

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

    bltz    $t1,NEXT    #leave when end of list 
    j   PRINTLIST
1

There are 1 answers

0
Rakholiya Jenish On BEST ANSWER

Some mistake I found is:

In GETLIST:

sw  $v0,0($a2)  #store in array
add $a0,$a0,4   #next number    <= instead write 'add $a2,$a2,4' if you want don't want to overwrite it.

Also the problem in printing list is that you are adding $a2 to store the number in the array. But, you forgot to re-assign the value of $a2 to the initial address of array. Hence it can be resolved with:

    add $t1,$t1,-1
    la $a2, array        <= line added
PRINTLIST: