user2803198
user2803198

Reputation: 47

While Loop in Mips (New to Mips)

How would I convert this code into Mips?

    int n = 100; int sum = 0; while (n>0) {
    sum = sum + n;
    n--; }

I have this so far and am not sure what to do to finish this.

    .data

    n: .word 100

    .text

    main:

    la $t0, n   
    lw $t1, 0(t0)
    li $so, 0

    Loop:
       bgt $t1, $zero, EXIT
       add $t1, $s0, $t1
       addi $t1, $t1, -1

       j Loop

    exit:

Upvotes: 0

Views: 37407

Answers (4)

user2855602
user2855602

Reputation: 47

I think bgt $t1, $zero, EXIT is the opposite of what you want. It seems like you want to convert while(n > 100), it would help if you make another method to do the codes inside of the while loop, then bgt $t1, $zero, . Correct me if I'm wrong.

Upvotes: 0

Konrad Lindenbach
Konrad Lindenbach

Reputation: 4961

Change the line:

add $t1, $s0, $t1

To:

add $s0, $s0, $t1

Also, there is no need for use of the data segment. Just set $t1 using:

li $t1, 100

Upvotes: 3

klee17
klee17

Reputation: 13

Mips doesn't have loops per-say, instead what your going to do is use a jump statement with conditions and loop with that.

Upvotes: 0

Mike Spear
Mike Spear

Reputation: 882

"Mips" isn't a language. MIPS an Instruction Set Architecture (ISA). Are you trying to figure out how to turn the C code into MIPS assembly code?

This looks like a homework assignment from the Patterson and Hennessy textbook. If so, you should go to your professor's office hours to get help. Almost every university includes in its academic handbook a statement that it's unethical to ask for homework help online.

If your request isn't a homework assignment, then the best way to convert that C code into MIPS assembly code is with a compiler. For simple loops, the compiler will generate more effective code than you can generate by hand. For example, "gcc -march=native -O3" will generate code that optimizes for the exact CPU on which you're compiling, taking into account pipeline depth and cache latencies.

If you absolutely need to see the assembly code, use "gcc -S" to produce an assembly file.

Upvotes: 1

Related Questions