Non-recursive Fibonacci Sequence in Assembly
-
09-12-2019 - |
Question
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
Solution
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
OTHER TIPS
Your loop simplifies to this in pseudocode:
L1:
count = ecx; // count === 15
eax = total = val + prev; // prev = -1 => eax = 0. prev = 1 => eax = 2
prev = val; // sets prev = 1, val doesn't change so prev = 1 after the first iteration
As you can see, eax = val + prev will evaluate to 2 once prev gets set to 1.
You should elaborate on the specification of your problem. How many integers do you want to print out? Is this what count = 15 is for? In that case you need to be decreasing count with every iteration and checking to see that it is non-zero.
As for the Fibonacci sequence, you should be doing something like this in your loop:
// lets say that eax is the current integer in the sequence and prev is the previous integer
// then the next integer = eax + prev
ebx = eax + prev
prev = eax
eax = ebx