prog8/examples/fibonacci.p8

46 lines
1.2 KiB
Plaintext
Raw Normal View History

2019-01-27 00:02:45 +00:00
%import c64utils
%zeropage basicsafe
2019-01-27 00:02:45 +00:00
; This example computes the first 20 values of the Fibonacci sequence.
; It uses the feature that variables that don't have an initialization value,
; will retain their previous value over multiple invocations of the program or subroutine.
; This is extremely handy for the Fibonacci sequence because it is defined
; in terms of 'the next value is the sum of the previous two values'
2019-07-29 21:11:13 +00:00
main {
2019-01-27 00:02:45 +00:00
sub start() {
c64scr.print("fibonacci sequence\n")
fib_setup()
2019-07-31 20:15:20 +00:00
for A in 0 to 20 {
2019-01-27 00:02:45 +00:00
c64scr.print_uw(fib_next())
c64.CHROUT('\n')
}
2020-03-12 23:50:50 +00:00
check_eval_stack()
2019-01-27 00:02:45 +00:00
}
sub fib_setup() {
; (re)start the sequence
main.fib_next.prev=0
main.fib_next.current=1
}
sub fib_next() -> uword {
uword prev ; no init value so will retain previous value
uword current ; no init value so will retain previous value
uword new = current + prev
prev = current
current = new
return prev
}
sub check_eval_stack() {
if X!=255 {
c64scr.print("stack x=")
c64scr.print_ub(X)
c64scr.print(" error!\n")
}
}
2019-01-27 00:02:45 +00:00
}