Non-recursive Fibonacci Sequence in Assembly

seiryuu10 picture seiryuu10 · Mar 7, 2012 · Viewed 8.5k times · Source

In some homework, I have to create a Fibonacci Sequence program in Assembly. I created this code, but it doesn't seem to be working correctly and I am not sure as to why. I believe that I am doing this correctly, but EAX remains "2" every loop.

    INCLUDE Irvine32.inc
    .data
        prev DWORD ?
        next DWORD ?
        val DWORD ?
        count DWORD ?
        total DWORD ?

        myMsg BYTE "Fibonacci Sequence ",0dh,0ah,0

   .code
    main PROC
       mov ecx,15
       mov val,1
       mov prev,-1
       mov eax,1
       mov edx,OFFSET myMsg
       call WriteString

    L1:
       mov count,ecx
       mov ebx,val
       add ebx,prev
       mov total,ebx
       mov ebx,val
       mov prev,ebx
       mov eax,total
       mov val, ebx
       call WriteInt
       call Crlf
       loop L1

    exit
    main ENDP
    END main

Answer

pät picture pät · Mar 7, 2012

Could look like this (untested):

    mov  ecx, 15
    mov  eax, 0    ;a = 0
    mov  ebx, 1    ;b = 1
_fib:
    mov  edx, eax 
    add  edx, ebx  ;sum = a + b
    mov  eax, ebx  ;a = b
    mov  ebx, edx  ;b = sum
    loop _fib