user2848403
user2848403

Reputation:

MIPS programming basic for-loop

I am currently writing a mips program which does factorial. I have written the factorial example in java, and have also have the MIPS program below the java code. I have the majority of the MIPS written out, but am confused why it is not processing correctly. Any tips would be greatly appreciated.

    Java code for the iteratve factorial algorithm:
import java.util.Scanner;
public class FactorMachine {
    public static void main(String[] args) {
        int input;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter an integer to be factored: ");
        input = in.nextInt();
        {
            int x, factorial = 1;
            for (x = input; x > 1; x--)
                factorial *= x;
            System.out.println("Factorial #" + input + " is " + factorial);
        }
    }
}

MIPS CODE:

    .data
p1: .asciiz "Enter an integer to be factored: "
ans1:   .asciiz "Factorial # "
ans2:   .asciiz " is "
ans3:   .asciiz "\n\n"

    .text
    .globl main

main:   li $v0, 4
    la $a0, p1
    syscall

    li $v0, 5
    syscall
    move $t0, $v0   #this is input

    li $t1, 1       #initilize factorial
    move $t2, $t0       #initilize x


loop:
    blt $t2, 1, done
    sub $t2, $t2, 1
    mul $t3, $t1, $t0
    j loop



done:
    li $v0, 4
    la $a0, ans1
    syscall

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

    jr $ra

Upvotes: 1

Views: 1202

Answers (1)

Michael
Michael

Reputation: 58427

Let's look at what the Java code does (I changed X *= Y to X = X * Y for clarity):

    for (x = input; x > 1; x--)
        factorial = factorial * x;

Now let's look at your assembly code:

move $t2, $t0       #initilize x
loop:
    blt $t2, 1, done
    sub $t2, $t2, 1
    mul $t3, $t1, $t0
    j loop

and what that would correspond to in Java:

for (x = input; x >= 1; ) {
    x--;
    temp = factorial * input;
}

Notice the differences? You're:

  1. Decrementing x before the multiplication, instead of after like in the original Java code.
  2. Multiplying by input ($t0) instead of by x ($t2).
  3. Storing the result of the multiplication in a different register instead of writing it back to factorial ($t1). So you'll always get the product of 1 * input, which of course equals input.

Upvotes: 1

Related Questions