title: Converting a C function to MIPS assembly
body: <p>I'm currently learning MIPS Assembly and I am attempting to convert the following C function into MIPS Assembly:</p>
  
  <pre><code>int count (int a[], int n, int x)
  {
  int res = 0;
  int i = 0;
  int j = 0;
  int loc[];
  for(i = 0; i != n; i++)
  if(a[i] == x)
  {
      res = res + 1;
      loc [j] = i;
      j = j + 1;
  }
  return res, loc;
  }
  </code></pre>
  
  <p>I've succeeded in converting most of it, and I believe I have successfully returned res (a value of 1), though I'm uncertain about returning loc (I also get a value of 1, and I don't think that's correct). However, I am having difficulty with this program and I am unsure as to how I can ensure that loc is returning the correct value or how to even code it to do so.</p>
  
  <p>Here is my Assembly code:</p>
  
  <pre><code>.data
  a: .word 5,6,7,8,9,10
  n: .word
  x: .word
  res: .word 0
  i: .word 0
  jj: .word 0
  loc: .space 40
  
  .text
  main:
  la $s0, a
  lw $s1, res
  lw $s2, x
  lw $t0, i
  lw $t1, jj
  lw $t2, n
  la $s3, loc
  li $t4, 6
  
  start:
  sll $t3, $t0, 2
  add $t5, $t3, $s0
  lw $t4, 0($t5)
  
  beq $t0, $t4, start
  addi $t0, $t0, 1
  beq $t0, $t2, exit
  
  addi $s1, $s1, 1
  sll $t7, $t1, 2
  add $t6, $s3, $t7
  sw $t0, 0($t6)
  addi $t1, $t1, 1
  
  exit:
  li $v0, 1
  add $a0, $s1, $zero
  syscall
  
  li $v0, 1
  add $a1, $s3, $zero
  syscall
  </code></pre>
  
  <p>Any help, pointers, or suggestions would be very much appreciated.</p>
  
  <p>EDIT: I've revised my code and now receive 0 for the <code>res</code> return and "268501028" for <code>loc</code>. Not sure where this number is coming from.</p>
  
  <pre><code>.data
  a: .word 5,6,7,8,9,10
  n: .word #n
  x: .word #x
  res: .word 0
  i: .word 0
  jj: .word 0
  loc: .space 40
  
  .text
  main:
  la $s0, a
  lw $s1, res
  lw $s2, x
  lw $t0, i
  lw $t1, jj
  lw $t2, n
  la $s3, loc
  li $t4, 6
  
  start:
  beq $t0, $t2, exit #for(i = 0; i != n; i++)
  bne $s0, $s2, else #if(a[i] == x)
  j start
  
  else:
  addi $s1, $s1, 1 #res = res + 1;
  sw $t0, ($t1) #loc [j] = i;
  addi $t1, $t1, 1 #j = j+1
  addi $t0, $t0, 1 #Increment i
  
  addi $s3, $s3, 4 #Setting next element for loc
  addi $s0, $s0, 4 #Setting next element for a
  j start
  
  exit:
  li $v0, 1
  move $a0, $s1
  syscall
  
  li $v0, 1
  move $a0, $s3
  syscall
  </code></pre>