examples/factorial.xyw
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 |
.include "devices.xyw"
; ;ain program: calculate and print factorial of 5
$5 fact JSRw
print8 JSRw
$0A terminal.output STB
end JMPw
; Factorial subroutine
; a8 -- | [xy]
.label fact
; Save argument to both registers
POPxy
.label fact.loop
PSHy $0 EQU fact.end0 JCNw
PSHy $1 EQU fact.end1 JCNw
; Decrement y and multiply
DECy PSHx PSHy MULx POPx
fact.loop JMPw
.label fact.end0
; Edge case: factorial of 0 is 1
$1
CLRxy
RTS
.label fact.end1
; Return result
PSHx
CLRxy
RTS
; Printing subroutine
; a8 -- | [xy]
.label print8
POPx
; If value is less than 10, print single digit
PSHx $A LTH print8.single JCNw
; Divide by 10: stack becomes [remainder, quotient]
PSHx $A DIV
; Save remainder to y for later
SWP POPy
; Call print8 recursively with quotient (still on stack)
print8 JSRw
; Print the saved remainder
PSHy $30 ADD terminal.output STB
CLRxy
RTS
.label print8.single
; Print single digit
PSHx $30 ADD terminal.output STB
CLRx
RTS
.label end
|