-1

here is my original code

main:    
    addi $sp, $sp, -8   # adjust stack for 2 items
    sw $ra, 4($sp)      # save return address
    sw $a0, 0($sp)      # save argument
    slti $t0, $a0, 1    # test for n<1
    beq $t0, $zero, L1
    addi $v0, $zero, 1  # if so, result is 1
    addi $sp, $sp, 8    # pop 2 items from stack
    jr $ra          # and return
L1: addi $a0, $a0, -1   # else decrement n
    jal main        # recursive call
    lw $a0, 0($sp)      # restore original n
    lw $ra, 4($sp)      # and return address
    addi $sp, $sp, 8    # pop 2 items from stack
    mul $v0, $a0, $v0   # multiply to get result
    jr $ra          # and return

I want the initial value for n! which is n=2, $sp <= 0x0000 A0000

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Jinho
  • 1
  • 1
  • not sure what you are asking, maybe you may want to move your current code into some procedure like `factorial:` (basically just renaming `main`), and create new `main`, which will set `a0` to initial value (2?), a do `jal factorial` and then it will use the MARS syscall to terminate (v0=10 I think from head). Do you mean this? – Ped7g Sep 24 '18 at 09:33
  • Don't vandalize your questions by removing all the code. That makes them meaningless / harder to understand. – Peter Cordes Sep 27 '18 at 05:44
  • @Peter Cordes, Sorry, my professor asked me to delete it. Because it's part of a assignment and other students could copy it without trying to solve... I tried to delete the question but I couldn't. Sorry.. – Jinho Sep 27 '18 at 12:30

1 Answers1

1

Make a separate function that you call from main, instead of making main itself recursive.


Or use the first arg of int main(int argc, char **argv) as n.

So you'd run your program with ./fac $(seq 2 4) to run it with $a0 = 4. What does int argc, char *argv[] mean?

The Unix seq 2 4 command prints 2 3 4, so the command has 3 arguments plus the implicit first arg (the command name), thus the C startup code will pass 4 to main as the argc argument.

Using ./foo $(seq number) is a convenient hack for messing around with hand-written asm, to avoid writing int-parsing code and have your program start with a binary integer already in a register (or in memory on some other platforms, like _start instead of main in the x86-64 System V ABI).

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847