jfisk
jfisk

Reputation: 6215

while loop in MIPS

Im trying to make a basic while loop example im preperation for my next assignment and im stuck in an infinite loop. $t3 never reaches to 3, or its not detecting that its at 3. What am i doing wrong here? Thanks!

.data           #data segment


msg1:.asciiz "please enter a number to convert to ASCI:  "
    nl:.asciiz "\n"
msg2:.asciiz "done!  "



.text           # Code segment
.globl main     # declare main to be global
main: 

    la $a0,msg1       # $a0 := address of message 1

    li $v0,4               # system call, type 4, print an string
    syscall

    li $t3,0 #initial value of $t3


    li $v0,5
    syscall #read an int

loop:

    la $a0,msg1       # $a0 := address of message 1

    li $v0,4               # system call, type 4, print an string
    syscall


    addi $t3,$t3,1  

    beq $3,$t3,Exit # branch to the label Exit if $t3=3

    j loop # branch unconditionally to loop ($t3 != 0)  

Exit:   
    li $v0,10       # System call, type 10, standard exit
    syscall   

Upvotes: 1

Views: 7950

Answers (2)

Jeff
Jeff

Reputation: 7674

The problem is here:

beq $3,$t3,Exit

$3 is a register; it is not the value 3. It's referring to the contents of the $3 register, which is actually $v1, which holds a value of 0 because you haven't put anything in there. So instead of comparing to a value of 3, you're comparing to 0. (It's not actually an infinite loop, since $t3 will eventually wrap around to 0, but you get the idea.)

MIPS lacks an instruction for comparing with an immediate, so you need to load the value 3 into a register first.

Add this line before the loop, because you only need to load the value once:

li $t4, 3

And change your compare to this:

beq $t4, $t3, Exit

This will get you out of the loop. Your program will then print msg1 three times and exit, which I suspect isn't what you want, but hopefully this lets you continue finishing up.

Upvotes: 1

gusbro
gusbro

Reputation: 22585

If you want to compare a register with an immediate and branch according to this comparison you have to use two instructions, slti and any of the branch instructions. The instruction slti $t, $s, imm will set register $t to 1 if the contents of $s is less than the immediate, and zero otherwise.

Therefore, to branch when register $t3 is equals to 3 (assuming it starts with 0 and increments on each loop) you should do

  slti $a0, $t3, 3  # Sets $a0 to 1 if $t3 < 3, 0 otherwise
  beq $a0, $0, loop # Jumps to 'loop' when $t3 < 0

Upvotes: 0

Related Questions