Store multiples off 11 in an array up to 1000 in MIPS

73 views Asked by At

(MIPS) I'm trying to store multiple's of 11 up to 1000 in an array and then trying to print them out in a sperate loop (I know i can do it a one loop all together)

.data

array11 : .space 360
.text




while :
    beq $t0, 360,exit
    addi $t0, $t0, 4
    addi $s0, $s0, 7
    sw $s0,array11 ($t0)
    
    
    j while

addi $t0, $zero, 0
exit:
loop :
    beq $t0, 360,exit
    addi $t0, $t0, 4
    lw $t6, array11($t0)
    
    li $v0, 1
    move $a0, $t6
    syscall
    j while

1

There are 1 answers

0
puppydrum64 On

You've got the right idea for how to do two separate loops, but there are a few problems with what's in those loops. I'll go through the code, one step at a time and come to a possible solution:

.text

while :
    beq $t0, 360,exit

To start with, your program begins with the first instruction after the .text declaration. Therefore the first thing you do in your program is compare $t0 to 360. The problem with that is, there's no way of knowing what value $t0 holds. Your operating system uses registers just like your program does, and so it could contain anything. Presumably you're trying to loop from 0 to 360, so you need to set $t0 to 0 before you start comparing it.

.text
move $t0,$zero
while:
    beq $t0, 360,exit
    addi $t0, $t0, 4
    addi $s0, $s0, 7
    sw $s0,array11 ($t0)
    
    
    j while

Now let's move on to the loop itself. The syntax you're using here sw $s0, array11($t0) could work, but there's no guarantee, as offset values have a limited range. It depends on what the address of array11 happens to be - and you don't want to rely on that if you don't have to. It's better to write it like this. We'll use the register $t2 for the loop counter

.text
la $t0,array11
move $t2,$zero
while:
   
   beq $t2,360,exit
   addi $t0,$t0,4  #increment pointer
   addi $t2,$t2,1  #increment loop counter
   addi $s0,$s0,7  #???
   sw $s0,0($t0)   #store in array
   j while

This, I'm not sure I understand. Why add 7 to $s0 if the goal is to output multiples of 11? Here's what I'd do to fix that.

.text
la $t0,array11
move $t2,$zero
move $s0,$zero
while:
   beq $t2,360,exit
   addi $t0,$t0,4  #increment pointer
   addi $t2,$t2,1  #increment loop counter
   addi $s0,$s0,11 #next multiple of 11.
   sw $s0,0($t0)   #store in array
   j while

Now that this is working, you can reduce the number of instrutions by changing how your loop is structured.

.text
la $t0,array11
li $t1,360
move $t2,$zero
move $s0,$zero
while:
   addi $t0,$t0,4     #increment pointer
   addi $t2,$t2,1     #increment loop counter
   addi $s0,$s0,11    #next multiple of 11.
   sw $s0,0($t0)      #store in array
   bltu $t2,$t1,while #loop while $t2 < 360

This version effectively merges the j while and beq $t0,360,exit into one instruction which will make your loop faster.