; fib.asm===================== ; ; this file contains main program and subroutine ; which will calculate the fibonacci number for a ; given input, according to the following fomula: ; ; C(1) = 1 ; C(2) = 1 ; C(n) = C(n-1) + C(n-2) ; ; the subroutine takes (n) as its input and ; returns C(n) ;======= ; data area org $0000 Num: db $8 Cn: db $0 ; set up the program start and the stack, ; as well as the stop bit so stop will work. org $0900 start: lds #$08ff tpa anda #$7f tap ;initialise registers so that storing them ;won't upset the simulator clra clrb ldy #0 ldaa Num ; Load the number psha ; push as a paramater psha ; push a space for C(n) jsr fibn ; call the subroutine pula ; pul the result staa Cn ; store the answer pula ; clean the stack stop ; and we're done ; the subroutine starts here. ; stack offsets - we don't need local variables. pn equ !7 pCn equ !6 fibn: ; start by preserving registers and ; establish Y as the frame pointer ; note, we don't use X. psha pshb pshy tsy ; begin evaluation. ; if n is 1, return "1" if1: ldaa #!1 cmpa pn,Y ;compare pn to 1 bne if2 ;if different, go on ldab #!1 ;if same, put "1" in b jmp sbdone ; if n is 2 return "1" if2: ldaa #!2 cmpa pn,Y ;compare pn to 2 bne else ;if different, go on ldab #!1 ;if same, put "1" in b jmp sbdone ; if n isn't 1 or 2, call subroutine with n-1 ; and n-2 else: ldaa pn,Y ;load n into a deca ;get n-1 psha ;push paramater psha ;push ret value jsr fibn ; call sub pulb ;pull resut pula ;clear stack deca ;get n-2 psha ;push paramater psha ;push ret value jsr fibn ; call sub pula ;pull result aba ;add it to prev. result tab ;put answer in B pula ;clean stack ; done, so store the return value and return from ; the subroutine. sbdone: stab pCn,Y puly pulb pula rts org $FFFE reset: dw start