-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAssemblyEx-14.asm
64 lines (48 loc) · 994 Bytes
/
AssemblyEx-14.asm
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
59
60
61
62
63
64
.data
promptMessage: .asciiz "Enter a number to find its factorial: "
resultMessage: .asciiz "\nThe factorial of the number is "
theNumber: .word 0
theAnswer: .word 0
.text
.globl main
main:
#Read the number from the user.
li $v0, 4
la $a0, promptMessage
syscall
li $v0, 5
syscall
sw $v0, theNumber
#Call the factorial function
lw $a0, theNumber
jal findFactorial
sw $v0, theAnswer
#Display the results
li $v0, 4
la $a0, resultMessage
syscall
li $v0, 1
lw $a0, theAnswer
syscall
#Tell the OS that this is the end of the program
li $v0, 10
syscall
#-------------------------------------------------------------
.globl findFactorial
findFactorial:
subu $sp, $sp, 8
sw $ra, ($sp)
sw $s0, 4($sp)
#Base case
li $v0, 1
beq $a0, 0, factorialDone
#findFactorial(theNumber - 1)
move $s0, $a0
sub $a0, $a0, 1
jal findFactorial
mul $v0, $s0, $v0
factorialDone:
lw $ra, ($sp)
lw $s0, 4($sp)
addu $sp, $sp, 8
jr $ra