user9318203
user9318203

Reputation:

MIPS Assembly while loop

I am currently learning MIPS and while doing some exercises I came across one which is to write the Fibonacci sequence first in Java then convert it to MIPS Assembly. I only can use beq, bne and slt My Java code is the following:

    int n = 50; F_MAX  v
    int t1 = 0;
    int t2 = 1;
    int sum = 0;
    while(t1 <= n)
    {
      System.out.print(t1 + " ")
      sum = t1 + t2
      t1 = t2
      t2 = sum;
     }

Meaning that if n = 50 if should print all the numbers before 50 (0; 1; 1; 2; 3; 5; 8; 13; 21; 34)

My MIPS Assembly code is:

      la $s0, F_MAX
      lw $s0, 0($s0)         #$s0 = int n = F_MAX (50);



  addi  $t1, $zero, 0     # $t1 = int t1 = 0;
  addi  $t2, $zero, 1     # $t2 = int t2 = 1;
  addi  $t3, $zero, 0     # $t3 = int sum = 0


  while:

        beq $t1, $s0, Exit  #if t1 == 50 exit the program

        addi $v0, $zero, 1      # syscall code to print integer
        add $a0, $zero, $t1     # t1 to be printed
        syscall                 # print t1

        add $t3, $t1, $t2
        addi $t1, $t2, 0
        addi $t2, $t3, 0

        addi  $v0, $zero, 4     # syscall code to print a string
        la  $a0, COMMA
        syscall                 # print a comma (and a space)


        j while

Exit:
li $v0, 10
syscall

But for some reason, it gives me overflow and prints all the possible positive numbers and I cannot figure out why.

Upvotes: 1

Views: 3592

Answers (1)

user9318203
user9318203

Reputation:

So here is the updated code: As the condition t1== 50 never was met it alwasys was false I had to use slt and bne instructions.

     la $s0, F_MAX
     lw $s0, 0($s0)                    #$s0 = int n = F_MAX (50);



     addi  $t1, $zero, 0               # $t1 = int t1 = 0;
     addi  $t2, $zero, 1               # $t2 = int t2 = 1;
     addi  $t3, $zero, 0               # $t3 = int sum = 0


           while:



           addi $v0, $zero, 1           # syscall code to print integer
           add $a0, $zero, $t1          # t1 to be printed
           syscall                      # print t1

           add $t3, $t1, $t2
           addi $t1, $t2, 0
           addi $t2, $t3, 0

           addi  $v0, $zero, 4          # syscall code to print a string
           la  $a0, COMMA
           syscall                      # print a comma (and a space)

           slt $t4, $t1, $s0            #if t1 < 50 $t4 = 1
           bne $t4, $zero, while        #if $t4 != $zero goto while

           slt $t4, $s0, $t1            #if 50 < $t1 $t4 = 1
           bne $t4, $zero, Exit         #if $t4 != $zero goto Exit

  Exit:
  li $v0, 10
  syscall

Upvotes: 1

Related Questions