A Sample Program: Finding Fibonacci Numbers


The following program generates and prints up to N Fibonacci numbers or to unsigned “overflow” (carry), which ever occurs first.
Fibonacci.asm
 TITLE Fibonacci Numbers              (Fibonacci.asm)
 INCLUDE Irvine32.inc
 .data
   prompt1  BYTE   "Find the first N Fibonacci numbers."
            BYTE   0Dh, 0Ah, "Enter the value of N (positive integer):  ", 0 
   prompt2  BYTE   0Dh, 0Ah, "Overflow at N = ", 0
   prompt3  BYTE   "  ", 0
   n        DWORD  ?
 .code
 main PROC
     call  Clrscr
     mov   edx, OFFSET prompt1
     call  WriteString
     call  ReadInt
     mov   n, eax
     call  Crlf
     mov   esi, 1                ; esi = 1, 2, 3, 4, 5, 6,  7, ...
                                 ; eax = 1, 1, 2, 3, 5, 8, 13, ...
     mov   edi, 1                ; edi = 1, 2, 3, 4, 5, 1,  2, ...
     mov   ecx, n                ; Computes and prints N numbers.
     mov   eax, 1                ; Initializes Fib(1) = 1.
     mov   ebx, 0                ; Fib(2) = Fib(1) + 0.
 L1: add   eax, ebx              ; Generates the next number.
           ; Jumps if carry (overflow).
     cmp   edi, 6                ; Prints 5 values each line.
     jne   L2
     mov   edi, 1                ; Advances to the next line.
     call  Crlf                  ; Prints newline.
 L2: call  WriteDec              ; Prints Fib(esi). 
     mov   edx, OFFSET prompt3
     call  WriteString           ; Prints spaces.
     xchg  eax, ebx              ; Sets up the sequence.
     inc   esi
     inc   edi
     loop  L1
     jmp   L4                    ; end of loop
 L3: mov   edx, OFFSET prompt2   ; overflow
     call  WriteString           ; Prints overflow.
     mov   eax, esi
     call  WriteDec              ; Prints N.
 L4: call  Crlf
     call  Crlf
     exit
 main ENDP
 END main
           

An Execution Example
Find the first N Fibonacci numbers.
Enter the value of N (positive integer):   10 

1  1  2  3  5
8  13  21  34  55
Note that you may not jump out of a loop and jump back into the loop later. It may mess up the register.


      “I’m not arguing, I’m just explaining why I’m right.”    
      ― Unknown