November 28, 2009

Finding N-th Fibonacci number and summation up to n-th fibonacci number in series using assembly language.

      This code represents an example of finding Fibonacci number and sum of Fibonacci series up to n-th number. It is written in assembly language and simulated using emu8086 emulator. Though it is a general program, it cannot find more than 8-bit binary number, the reason is 8086 processor registers are 8-bit.

      This is a general program for finding any number in Fibonacci series up to its limit and finding summation of two Fibonacci numbers written in assembly code and I checked this code with emu8086 emulator. Here it goes:

Code:
         
; this program calculates the n-th Fibonacci number
; and the sum of the fibonacci series upto n-th number
;the n-th number must be given in CX register

    CODE SEGMENT
    ASSUME CS:CODE,DS:CODE
    ORG 100H

    ;S=F1+F2 // these 3 lines are algorithom
    ;F1=F2;
    ;F2=S;

    XOR AX,AX      ; clearing garbage value if any
    XOR BX,BX
    XOR DX,DX
    XOR CX,CX

    MOV AL,1         ; first number in series
    MOV AH,1         ; second number in series
    MOV CX,6         ;calculating upto sixth number in
                     ;fibonacci series
    MOV DL,0
    MOV SI,0         ; SI is used as index
    MOV SRS[SI],AL   ; putting first and second value
                     ; in array
    INC SI
    MOV SRS[SI],AH
    INC SI           ;increment to point first calculated
                     ;value store point
    FIB:             ;starting the fibonacci number
                     ;calculating loop
    PUSH AX          ; AH contains second number,it
                     ;will be changed
                     ; during addition, so saving it

     ADD AH,AL       ; S=F1+F2, next number in series
     MOV DL,AH       ;saving the calculated number
     MOV SRS[SI],DL  ; copying to the array
     INC SI          ; pointing the next position in
                     ;the array
     POP AX          ; restoring the second number

     MOV AL,AH       ; F1=F2
     MOV AH,DL       ; F2=S
     LOOP FIB        ; loop until all number is calculated

     MOV CX,6H
     MOV SI,0        ; pointing to first index in the array

     ADD:            ; summation loop
     ADD BL,SRS[SI]  ; SRS is array for number stored
     INC SI
     LOOP ADD

    ;ORG 500H ,      comment bcoz EMU dont support two ORG

     SRS DB 12 DUP(0) ; twelve position array for fib series
                      ; now maximum 12 number can be
                      ;calculated
                      ;number should be increased to
                      ;increase capacity

     CODE ENDS
       END

You may also find these interesting:
1.Sorting maximum and minimum from an array using Assembly
2.Energy saving lamp, what and how, curse or blessing?
3.Principle of induction machine-analogy approach