-2

I am trying to convert this for loop into MIPS assembly language and i am not sure how exactly to tackle this question. I tried using youtube to understand the concept of it and I am still strugling with it.

here is the C code:

int sum = 0;
for (int i = 1; i <= 10; i ++){
    if (i & 1) sum = sum + i * i;
    else sum = sum + i;
} 

I tried converting but i am just not sure where to start it.

expecting to get MIPS code with explanation in possible so I can learn from it!

Prectron
  • 282
  • 2
  • 11
Doubt
  • 1
  • 1
  • Its always good to do a search before posting here. Many questions already have answers. See, for example, [this question](https://stackoverflow.com/q/9155336/14853083) – Tangentially Perpendicular Nov 16 '22 at 21:04
  • Can you be more specific about your inquiry? Is it about how to translate a for-loop to assembly? How do to an if-then-else construct in assembly? How to do &1? ... – Erik Eidt Nov 17 '22 at 01:12
  • I am suppose to convert this for loop into an assembly using registers and stuff. – Doubt Nov 19 '22 at 02:57

1 Answers1

0

I assume that you are doing the bitwise and operator with 1 to indicate if the current 'i' is odd or even. What you can do is the following :

    .text
li  $t0, 1  #is for counting or i in this case
li  $t1, 1  #for if statements condition
li  $v0, 0  #output register

    forLoop:
bgt $t0, 10, end
andi    $t2, $t0, 1     #and opertion   
beq $t2, 1, odd #if andi resulted in one do the odd computation if not it is even
add $v0, $v0, $t0
addi    $t0, $t0, 1
j   forLoop
    odd:
mul $t2, $t0, $t0   #t2 is like a temporary register can be overwritten, square of i
add $v0, $v0, $t2
addi    $t0, $t0, 1
j   forLoop

    end:
move    $a0, $v0
li  $v0, 1
syscall
li  $v0, 10
syscall 

This implementation is correct however the "right" implementation should use stack pointer and jump and link command for calling the function. This example has the sole purpose for showing the logic behind it.

PoePew
  • 37
  • 7