browser

factorialw.xyw

factorialw.xyw
calendarsave
.include "lib/macros.xyw"

; Main program: calculate and print factorial of 7
$0007 fact JSRw 
putdw JSRw
NL
HLT

; Factorial subroutine
; w ->
.label fact
  ; Save argument to both registers
  POPxyw
  .label fact.loop 
    ; Need to work with 16-bit comparisons
    PSHyw $0000 EQUw fact.end0 JCNw
    PSHyw $0001 EQUw fact.end1 JCNw
    ; Decrement y and multiply
    DECyw PSHxw PSHyw MULxw POPxw
    fact.loop JMPw
  .label fact.end0
    ; Edge case: factorial of 0 is 1
    $0001
    RTS
  .label fact.end1
    ; Return result
    PSHxw
    RTS

.include "lib/putdw.xyw"