How would I write a program that will display the first 24 values in the Fibonacci series in assembly language?
If anyone could help me I would greatly appreciate it, I'm confused with the code in assembly.
How would I write a program that will display the first 24 values in the Fibonacci series in assembly language?
If anyone could help me I would greatly appreciate it, I'm confused with the code in assembly.
Well, you do it pretty similarly to the way you would in most other languages, something like this:
for loop counter = 1 to 24 do
next_number = fibonacci(previous, previous2)
print(next_number)
previous2 = previous
previous = next_number
The obvious differences from other languages include:
I left two blank spaces because the code depends on the system where it's going to run (you didn't specify the compiler and operating system).
I haven't tested the code but I think it will work.
mov eax, 0 ; first number
mov ebx, 1 ; second number
; edx will contain the third number (eax + ebx )
mov ecx, 24 - 2 ; print 24 numbers (don't count the first
and second because they are printed in the begining)
mov edx, eax
call print_number ; print the first number
mov edx, ebx
call print_number ; print the second number
fibo:
mov edx, eax
add edx, ebx ; edx = eax + ebx
call print_number
; now we have the third number in edx
; eax = 1st, ebx = 2nd, edx = 3rd
; to prepare eax and abx for the next iteration, shift the values to the right
; eax = 2nd, ebx = 3rd, edx = ?
mov eax, ebx
mov ebx, edx
loop fibo
; TO DO: exit program
print_number:
; TO DO: edx contains the number, print it
return
Hope it helps.
A number in Fibonacci series is the sum by the two numbers preceding it. To keep it simple you can store these numbers in an array with the first two element set to 1. esi and edi could point to n-1 and n-2, so fibonacci(n) = [esi] + [edi]] right? In pseudocode it looks like:
fibonacci DWORD 24 dup (?)
esi = fibonacci(0) // those are pointers to elements!
edi = fibonacci(1)
for x = 2 to 23
fibonacci(x) = [esi] + [edi]
esi += 4 // if you don't like DWORDs change this
edi += 4
end loop
you can keep x in the ecx register and fibonacci(x) in the eax register.
try this code it would work as per your requirements this answer makes use of a loop running for 24 times and the label looped is next which first takes the data from ax and bx and then adds it up these all functions are repeated for 24 times till the loop is completed.
data segment
org 0000h
arr dw 17h dup(0000h)
data ends
code segment
assume cs:code, ds:data
start: mov ax,data
mov ds,ax
mov cx,0018h
lea si,arr
inc si
mov [si],01h
next: mov ax,[si-1]
mov bx,[si]
add ax,bx
inc si
mov [si],ax
loop next
mov ah,4ch
int 21h
code ends
end start
end