-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleyla_abdullayeva_mips_code.asm
73 lines (57 loc) · 1.49 KB
/
leyla_abdullayeva_mips_code.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
65
66
67
68
69
70
71
72
73
.text
.globl main
main:
# Register assignments
# $s0 = N
# $s1 = counter (i)
# $s2 = sum
# Print msg1
li $v0,4 # print_string syscall code = 4
la $a0, msg1
syscall
# Get N from user and save
li $v0,5 # read_int syscall code = 5
syscall
move $s0,$v0 # syscall results returned in $v0
# Initialize registers
li $s1, 0 # Reg $s1 = counter (i)
li $s2, 0 # Reg $s2 = sum
# Main loop body
loop: addi $s1, $s1, 1 # i = i + 1
# Call add function
move $a0, $s2 # Argument 1: sum ($s2)
move $a1, $s1 # Argument 2: i ($s1)
jal add2 # Save current PC in $ra, and jump to add2
move $s2,$v0 # Return value saved in $v0. This is sum ($s2)
beq $s0, $s1, exit # if i = N, continue
j loop
# Exit routine - print msg2
exit: li $v0, 4 # print_string syscall code = 4
la $a0, msg2
syscall
# Print sum
li $v0,1 # print_string syscall code = 4
move $a0, $s2
syscall
# Print newline
li $v0,4 # print_string syscall code = 4
la $a0, lf
syscall
li $v0,10 # exit
syscall
add2: # Store registers on the stack that we will overwrite (just $s0)
addi $sp,$sp, -4 # Adjust stack pointer
sw $s0,0($sp) # Save $s0 on the stack
# Run the function
add $s0,$a0,$a1 # Sum = sum + i
# Save the return value in $v0
move $v0,$s0
# Restore overwritten registers from the stack
lw $s0,0($sp)
addi $sp,$sp,4 # Adjust stack pointer
# Return from function
jr $ra # Jump to addr stored in $ra
.data
msg1: .asciiz "Number of integers (N)? "
msg2: .asciiz "Sum = "
lf: .asciiz "\n"