-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursive_Factorial.asm
More file actions
58 lines (46 loc) · 1.02 KB
/
Recursive_Factorial.asm
File metadata and controls
58 lines (46 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Saksham Johari-----13/10/21
# E20CSE076
# Q3
.data
inp: .asciiz "Enter number to compute factorial: "
res: .asciiz "\nFactorial is: "
init: .word 1
.text
main:
lw $s0,init
li $v0,4
la $a0,inp
syscall
li $v0,5
syscall
move $a0,$v0
jal fact
move $t0,$v0
li $v0, 4
la $a0, res
syscall
li $v0, 1 # printing the result returned
move $a0, $t0
syscall
j exit
fact:
addi $sp, $sp, -8 # base case -- still in parent's stack segment
sw $s0, 4($sp) # adjust stack pointer to store return address and argument
sw $ra, 0($sp) # save $s0 and $ra
bne $a0, 0, el
addi $v0, $zero, 1 # return 1
j fact_ret
el:
move $s0, $a0
addi $a0, $a0, -1 # x -= 1
jal fact
multu $s0, $v0 # return x*Fact(x-1)
mflo $v0
fact_ret:
lw $s0, 4($sp)
lw $ra, 0($sp)
addi $sp, $sp, 8
jr $ra
exit:
li $v0, 10 # Program termination block
syscall