roee attias
roee attias

Reputation: 125

How to print the first 20 elements in the Fibonacci series (assembly 8086)?

I am trying to write a code that runs a loop that prints the first 20 numbers in the Fibonacci series, but I don't know how I can solve it. I tried many ways.

org 100h

mov ax, 0
mov bx, 1
mov cx, 20

start:        

call print_num ; this is function that print the value that inside ax register
PRINTN         ; this is print new line
mov dx, ax
add ax, bx   
loop start
   
mov ah, 0

int 16h
ret 

include magshimim.inc ; this is a private library

Someone knows how I can do this?

Upvotes: 1

Views: 718

Answers (1)

Sep Roland
Sep Roland

Reputation: 39516

Depends on how we want the sequence to start.

Even Fibonacci himself started his sequence from 1,2,3,5,8,...
See the Wikipedia article https://en.wikipedia.org/wiki/Fibonacci_number


Your code after applying the correction suggested by @ecm:

org 100h

  mov ax, 0
  mov bx, 1
  mov cx, 20
start:        
  call print_num
  PRINTN
  mov dx, ax
  add ax, bx   
  MOV BX, DX
  loop start
  mov ah, 0
  int 16h
  ret 

include magshimim.inc

It will output:

0,1,1,2,3,5,8,13,...

Sometimes we don't want to start with the zero. Next code works that way:

org 100h

  mov  ax, 1
  xor  bx, bx
  mov  cx, 20
start:        
  call print_num
  PRINTN
  xchg ax, bx
  add  ax, bx   
  loop start
  mov  ah, 00h  ; BIOS.WaitKey
  int  16h      ; -> AX
  ret

include magshimim.inc

It will output:

1,1,2,3,5,8,13,...

Some more info about this in Simple fibonacci printer in 8086 assemlby

Upvotes: 1

Related Questions