and this is my codes:
.data
mesg1: .asciiz "The value you entered is less than zero. This program only works with values greater than or equal to zero."
mesg2: .asciiz "You input: "
nl: .asciiz "\n"
mesg3: .asciiz "The factorial is: "
mesg4: .asciiz "do you like to do this again? "
userInput: .space 10
yes: .byte 'Y'
.text
main:
li $v0, 5 # user input
syscall
move $t0, $v0
li $t2, 0 # load 0 into t2 for comparsion
li $t3, 1 # load 1 into t3 for bne
slt $t1, $t0, $t2 # store result in t1
beq $t2, $t3, error # if input is smaller than 0, jump to error
bne $t2, $t3, Fact # if input is greater or equal to 0, call factorial function
li $v0, 4 # print string
la $a0, mesg2 # print out mesg2
syscall
li $v0, 1 # print int
move $a0, $t0 # your input int
syscall
li $v0, 4 # print string
la $a0, nl # print out new line
syscall
li $v0, 4 # print string
la $a0, mesg3 # print out the factorial is
syscall
li $v0, 1 # print int
move $a0, $t4 # print factorial
syscall
li $v0, 4 # print string
la $a0, nl # print out new line
syscall
li $v0, 4 # print string
la $a0, mesg4 # ask if they want to do it again
syscall
li $v0, 8 # user input
la,$a0, userInput
li,$a1, 10
syscall
move,$t5,$v0
lw, $t6, yes
beq $t5,$t6,main # if yes, go back to step 1
bne $t5,$t6,end # if no, terminate
Fact:
move $a0,$t0 # move user inputs into a0
subi $sp,$sp,8 # make room for 2 registers
sw $ra,4($sp)
sw $a0,0($sp)
slti $t0,$a0,1 # if (n<1)
beq $t0,$zero,L1
addi $v0,$zero,1 # return 1
addi $sp,$sp,8 # pop 2 from stack (not restored)
move $t4, $v0 # save return value into t4
jr $ra
L1: # n-1
subi $a0,$a0,1
jal Fact # recursion
lw $a0,0($sp) # when we return back
lw $ra,4($sp)
addi $sp,$sp,8
mul $v0,$a0,$v0 # n*fact(n-1)
move $t4, $v0 # save return value into t4
jr $ra
error:
li $v0, 4 # print string
la $a0, mesg1 # print out error message
syscall
end:
li $v0, 10 # terminate program
syscall
How to modify it so it works but have to use the Fact: and L1: functions? I guess there's something wrong in the jr $ra? but dont know how to fix it...
User contributions licensed under CC BY-SA 3.0