Hello! I just started trying to get the grasp of Assembly a few days ago, so I decided to write a program to print the Fibonacci numbers up to the 25th one. I'm using NASM, and it's for the x86 processor. I came up with this code, but it'll loop infinitely, not just 25 times (which I set ECX to). It's probably a simple mistake, but thank you to anyone who looks through it for me!

SECTION .DATA
    fmt: DB '%d',10,0
    
SECTION .TEXT
    GLOBAL  _main
    EXTERN  _printf
_main:
    MOV     EBX,1
    MOV     EAX,0
    MOV     ECX,25     ;set loop counter to 25, right?
fib:
    PUSH    EBX
    ADD     EBX,EAX
    POP     EAX
    
    PUSH    EAX
    PUSH    fmt
    CALL    _printf
    ADD     ESP,8
    LOOP    fib       ;maybe put in the wrong spot?
end:
    MOV     EAX,0
    RET

EDIT: I just realized that _printf is probably messing with EAX, but how can I save it before and restore it after? A PUSH and POP before and after the _printf block still kept the infinite loop and messed with the signs on the number? I think...

I've had problems getting the LOOP instruction to work with NASM before. You might want to try replacing your loop instruction with this code:

SUB ECX, 1
CMP ECX, 0
JG fib

I finally got it. The fib code is a bit off anyways, but to fix the loop, I just needed to PUSH ECX right before my _printf block and POP it back after; It was getting messed with by the C function. Phew :)

This article has been dead for over six months. Start a new discussion instead.