0

I am trying to write code in assembly that will print out the proper sequence until the entered iteration is reached. I am unable to enter the for loop, I am unsure why, however, it may be due to improper use with the cmp <dst>, <src> call - I don't think that is why but it may be.

My data section looks like the following:

.data
    stmt1 db "Nathanial Mendes", 0Ah, 0

    prompt1 db "Enter maximum sequence count: ", 0
    fmt db "%d", 0

    sum db "Fib(%d) = %d", 0

    seq dd 0

This is what my code section looks like

.code 
    main PROC c
    push offset stmt1
    call printf

    ;Prompt for first int
    push offset prompt1
    call printf
    add esp, 4

    push offset seq
    push offset fmt
    call scanf
    add esp, 8

    ;Set up loop vars
    mov eax, 0 ; set i = 0
    mov ebx, 0
    mov ecx, 0
    mov edx, 0

;#############################
    beginloop:
    cmp eax, seq ; comparing the counter (eax) to the max iteration (seq) 
    jle endloop ; if it is false jump to the end of the loop

;#######
    ;code for Fib here

    ;print statement (prints out the current Fib, looks like Fib(iteration) = Fib_sum
    push eax
    push ebx
    push offset sum
    call printf
    add esp, 8

    ;next term calculations for the fib seq.
    add ecx, edx
    mov ebx, ecx
    mov ecx, edx
    mov edx, ebx
;#######
    ; set up next iteration of for-loop

    add eax, 1 ; add one to the iterator 
    jmp beginloop
;#######
    ;when the for loop is false
    endloop:

    ;Print (final) result
    push eax
    push ebx
    push offset sum
    call printf
    add esp, 8

;##########################################

    INVOKE ExitProcess,0
    main endp
end

Why it is that my for-loop never goes past the compare statement and goes directly to the endloop call?

  • 1
    Looks like it should enter once, but the rest of the code is wrong. `add esp, 8` should be `12` because you passed 3 arguments. Also `printf` is allowed to change `eax`, `ecx` and `edx` so all your locals will be overwritten. – Jester Nov 06 '19 at 23:56

1 Answers1

1

cmp eax, seq / jle endloop is if(i<=seq) break with i=0. So for non-negative seq, you never enter the loop.

You want the opposite break condition. Or put this loop condition at the bottom of your loop like an normal asm loop with the conditional branch at the bottom. (Why are loops always compiled into "do...while" style (tail jump)?)

As Jester commented, your code has other bugs, but that's the answer to this one. (I think Jester is counting it as "entering the loop" once when execution passes the beginloop: label and reaches your if() break at the top of the loop body.)

This looks like MASM syntax so seq without [] is still a memory operand, not comparing against the address as an immediate. I'd generally recommend using [] around memory operands in general.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847