Fibonacci sequence: Difference between revisions

Content added Content deleted
imported>Arakov
imported>KayproKid
m (→‎{{header|8080 Assembly}}: made 2nd example start from 0 instead of 1)
Line 251:
;-------------------------------------------------------
bdos equ 5 ; BDOS entry
cr equ 13 ; ASCII carriage return
lf equ 10 ; ASCII line feed
space equ 32 ; ASCII space char
conout equ 2 ; BDOS console output function
putstr equ 9 ; BDOS print string function
nterms equ 20 ; number of terms (max=24) to display
;-------------------------------------------------------
; programmain code begins here
;-------------------------------------------------------
org 100h ; load point under CP/M
lxi h,0 ; save command processorCP/M's stack
dad sp
shld oldstk
lxi sp,stack ; set our own stack
lxi d,signon ; print signon message
mvi c,putstr
call bdos
mvi a,10 ; teststart bywith displaying first 20Fib(0)
mloop: push a ; save our count (putdec will trash)
call fib
call putdec
mvi a,space ; separate the numbers
call putchr
pop a ; get our count back
inr a ; increaseincrement it by one
cpi 20nterms+1 ; have we reached our limit?
jnz mloop ; not yet;no, dokeep anothergoing
lhld oldstk ; we'reall done -; get CP/M's stack back
sphl ; restore it
ret ; back to command processor
;-------------------------------------------------------
; calculate nth Fibonacci number (max n = 24)
; entry: A = n
; exit: HL = Fib(n)
;-------------------------------------------------------
fib: mov c,a ; C holds n
lxi d,0 ; initialDE value forholds Fib(n-2)
lxi h,1 ; intiialHL value forholds Fib(n-1)
ana a ; Fib(0) is a special case
jnz fib2 ; n > 0 so calculate normally
xchg ; otherwise return with HL=0
ret
fib2: dcr c
jz fib3 ; we're done
push h ; save Fib(n-1)
dad d ; HL holds= Fib(n), soon to be Fib(n-1)
pop d ; FormerDE Fib= old F(n-1), now Fib(n-2)
jmp fib2 ; loopready untilfor donenext pass
fib3: ret
;-------------------------------------------------------
; console output of char in A register
;-------------------------------------------------------
putchr: push h
push h
push d
push b
mov e,a
mvi c,conout
call bdos
pop b
Line 316 ⟶ 320:
push d
push h
lxi b,-10
lxi d,-1
putdec2:
dad b
inx d
jc putdec2
lxi b,10
dad b
xchg
mov a,h
ora l
cnz putdec ; recursive call
mov a,e
adi '0'
call putchr
pop h
Line 336 ⟶ 340:
ret
;-------------------------------------------------------
; message and data area
;-------------------------------------------------------
signon: db 'FirstFibonacci 20 Fibonaccinumber numberssequence:',cr,lf,'$'
oldstk: dw 0
stack equ $+128 ; 64-level stack
Line 346 ⟶ 350:
{{out}}
<pre>
Fibonacci number sequence:
First 20 Fibonacci numbers:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
</pre>