1

I'm a beginner in assembly language. I'm using windows. I tried using the code from the second answer here:Recursive Fibonacci in Assembly to give me the nth Fibonacci number

Fibonacci: ; computes Fib(EAX) --> EAX; do not call with EAX==0
  CMP  EAX, 1      ; N<=1?
  JBE  exit        ; yes, we have the answer
  DEC  EAX         ; = N-1
  PUSH EAX         ; save N-1
  CALL Fibonacci   ; computing FIB(n-1)to EAX
  XCHG EAX,0[ESP]  ; swap FIB(n-1) for saved N-1 
  DEC  EAX         ; = N-2
  CALL Fibonacci   ; computing FIB(N-2) to EAX
  POP  ECX         ; = FIB(N-1)
  ADD  EAX,ECX     ; = FIB(N-1)+FIB(N-2)
  exit:
  RET

That part works, but I can't print the sequence F(0) to F(10)

    mov ecx,10
    mov ebx,0
print_fib:
    mov eax,ebx
    call fibonacci
    call print_int
    inc ebx
    loop print_fib
Community
  • 1
  • 1
Clark
  • 31
  • 6
  • Since you're already thinking about Fibonacci numbers, you might find http://stackoverflow.com/questions/32659715/assembly-language-x86-how-to-create-a-loop-to-calculate-fibonacci-sequence interesting. That's about a looping non-recursive implementation (because computing Fib(n) in O(Fib(n)) time is silly when you can compute it easily in O(n) time, or even O(log(n)) time if you want to get more complicated). It's useful as an exercise to write a working recursive function, but I wish people would pick an example where a recursive implementation actually made something simpler. – Peter Cordes Oct 22 '15 at 06:20

1 Answers1

4

Look at the Fibonacci routine more carefully (or step through it in a debugger), and you'll notice that it modifies ECX, which you rely on as a loop counter.

It's up to you how you want to fix that. You could e.g. push and pop ECX in your loop before/after the call to Fibonacci; or you could change Fibonacci so that it uses a different register:

pop edx
add eax,edx

or even:

add eax,[esp]   ; add the value at the top of the stack to eax
add esp,4       ; move the stack pointer the same distance as if we'd done pop r32
Michael
  • 57,169
  • 9
  • 80
  • 125