-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathask2.asm
More file actions
72 lines (57 loc) · 1.65 KB
/
ask2.asm
File metadata and controls
72 lines (57 loc) · 1.65 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#Author: Sotiris Karapiperis
#problem set 1 - exercise 2
#declare data
.data
#source code
.text
.globl main
main:
addi $a0, $zero, 1 #set first argument = 1
addi $a1, $zero, 10 #set first argument = 10
jal sum1 #call sum1(1,10)
#syscall to print the result
add $a0 ,$zero, $v0
li $v0, 1
syscall
#syscall to print space character
li $a0, 32
li $v0, 11
syscall
addi $a0, $zero, 1 #set first argument = 1
addi $a1, $zero, 10 #set first argument = 10
jal sum2 #call sum2(1,10)
#syscall to print the result
add $a0 ,$zero, $v0
li $v0, 1
syscall
#syscall to exit the program
li $v0, 10
syscall
#a0 = n, a1 = k
sum1:
add $t2, $zero, $zero #t2 = res = 0
for: slt $t3, $a1, $a0 # t3 = 1 if n > k
bne $t3, $zero, end #if n > k jump to end
add $t2, $t2, $a0 # res += n
addi $a0, $a0, 1 #n++
j for #iterate again the loop
end:
add $v0, $zero, $t2 #copy res to v0
jr $ra #return to caller
sum2:
addi $sp, $sp, -8 #make space to stack
sw $ra, 0($sp) #save ra
sw $a0, 4($sp) #save n
slt $t0, $a1, $a0 #t0 = 1 if n > k
beq $t0, $zero, recur #if n <= k jump to recur
add $v0, $zero, $zero #if n > k return 0
addi $sp, $sp, 8 #no need to load ra, a0 just restore stack pointer
jr $ra #return to caller
recur:addi $a0, $a0, 1 #n +=1
jal sum2 #call sum2(n + 1 , k)
lw $a0, 4($sp) #load a0
lw $ra, 0($sp) #load ra
addi $sp, $sp, 8 #restore stack pointer
add $v0, $v0, $a0 # res = n + sum2(n+1, k)
jr $ra #return to caller
.end main