Hello I have been practicing writing assembly language and I have been working on this seemingly simple code. I want to prompt the user for input then i want to take that input and put it into an array. Then i want to print out the array. I know I can just print them out without putting them in an array but this is just for my practice. Something is just not right though it wont print them back out.
.data
array: .space 400
prompt: .asciiz "Enter an integer (0 to quit) :"
text: .asciiz "After sorting, the list of integers is:"
.text
.globl main
main:
la $a1, array
li $v0, 4
la $a0, prompt
syscall
li $v0, 5
syscall
sw $v0, 0($a1)
addiu $a1, $a1, 4
beqz $v0, sort
j main
sort:
la $a1, $array
li $v0, 4
la $a0, text
syscall
loop:
lw $t0, 0($a1)
addiu $a1, $a1, 4
beqz $t0, done
li $v0, 1
move $a0, $t0
syscall
j loop
done:
please help me with what i am doing wrong. Oh and the zero is kind of the sentinal value when i hit a zero that means its the end of the input
Remember that branch and jump instructions on MIPS have delay slots. That is, the instruction directly following a branch or jump instruction is always executed.
It's possible that your assembler (gas?) is taking care of this for you by inserting NOPs
or re-ordering instructions. You could find out by disassembling the binary with objdump. If the assembler doesn't fix this for you, the easiest way to fix it by yourself is to insert a NOP
after each branch/jump.
The other thing that stands out is that you always reload $a1
with the address of array
before you read a new number. This means that every number you read will be stored at array[0]
, including the terminating 0. So your print loop will find 0 as the first value in the array and exit immediately.
You could fix that by changing the code to something like this:
main:
la $a1, array
read_numbers:
# Rest of code omitted for brevity...
beqz $v0, sort
j read_numbers