/
sumints.mvm
55 lines (42 loc) · 905 Bytes
/
sumints.mvm
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
main:
; Create the initial stack frame with room for given
; number of arguments and locals.
; create room for one local variable: you may want to increase this
enter 0, 2
; Local variables:
; 0: the value of N
; 1: current sum
; -- you can add other local variables --
ldc_i 5 ; this is the value of N
stlocal 0 ; store it in local variable 0
ldc_i 0 ; initial sum value
stlocal 1 ; store it in local variable 1
; Compute the sum of the integers 1..N
loop:
; while (N > 0) {
ldlocal 0 ; load N
ldc_i 0 ; constant 0
cmp ; compare them
jlte done
; sum = sum + N
ldlocal 1
ldlocal 0
add
stlocal 1
; N = N - 1
ldlocal 0
ldc_i 1
sub
stlocal 0
; }
jmp loop
done:
; print sum
ldlocal 1
syscall $println
pop
; Note: the ret instruction requires that there is
; at least one operand on the operand stack.
ldc_i 0 ; dummy value
ret
; vim:filetype=asm