user977154
user977154

Reputation: 1095

MIPS assembly for a simple for loop

I need to translate this C code to MIPS assembly. Here is the C code:

int tmp = 0; 
for (int  j = 0; j < 15; ++j) 
     tmp = tmp * 2 + 3

This is my MIPS assembly code. Is it a correct translation? If you see any mistakes I would really like to know.

# tmp = $v0
# j = $t0

.globl main

 main:
    li $v0,0

loop:
    bgt $t0,15,exit
    addi $t0,$t0,1
    mul $t1,$v0,2
    add $v0,$t1, 3
    j loop  

exit:

Upvotes: 14

Views: 132856

Answers (5)

Maria
Maria

Reputation: 67

    add $vo, $vo, $zero
    add $t0, $t0, $zero
LOOP:
    slti $t1, $t0, 15
    beq $t1, $zero, EXIT
    addi $t0, $t0, 1
    addi $t2, $zero, 2
    mul $t3, $v0, $t2
    addi $v0, $t3, 3
    j    LOOP
EXIT:

Upvotes: 0

Raul Batalha
Raul Batalha

Reputation: 1

.data
mensage: asciiz "Text Test"
newline: asciiz "\n"
.text

# tmp = $v0
# j = $t0
 
main:
    li $t0,0
    li $t1,0
    li $t3,0
loop:
    bgt $t0,15,exit
    addi $t0,$t0,1
    j loop
    mul $t1,$t1,2
    add $t3,$t1,3  
exit:
    li $v10,0
    syscall

Upvotes: -1

Meech
Meech

Reputation: 1

I also don't know what MIPS simulator you're running, but I know some of them don't constants and they demand you assign those to registers. So like bgt Rsrc1, Src2, label, normally if you put an integer in src2 the computer will translate that but I know for some you'll get an error doing add $v0, $t1, 3 as it won't translate add into addi. Same with mul. I know my SPIM simulator doesn't allow it.

Upvotes: 0

Richard Pennington
Richard Pennington

Reputation: 19965

You don't set j ($t0) to zero before the loop.

Upvotes: 3

MrD
MrD

Reputation: 2481

Your loop goes from 0 to 14, so your bgt instruction should be: bgt $t0,14,exit I think.

.

Upvotes: 11

Related Questions