Search code examples
loopsassemblymasmirvine32

Assembly endless loop [HOMEWORK]


I am working on a homework assignment where I need to randomly print 20 lines of 20 RANDOM characters to the screen. I am extremely new to assembly language and don't understand why my loop won't end, even though I have ecx set to 20 and am decrementing each time.

currently the screen prints the random letters correctly, but never stops printing.

My code is as follow:

INCLUDE Irvine32.inc
    .data
         buffer byte 20 dup(?) ;buffer of size 20 initialized ?
         L dword 20     ;length of size 20
    .code

    main proc

        l1:
            mov ecx,L ;ecx = 20
            call RandomString   ;call Random String
            dec ecx   ;ecx --
            cmp ecx,0 ;compare ecx to zero
            jne l1    ;jump if not equal back to l1

            call WaitMsg   ;press any button to continue

    exit
    main endp

   RandomString PROC USES eax ecx edx
       mov eax,26     ;eax = 26
       call RandomRange    ;call RandomRange
       add eax, 'A'   ;eax = random number between 0 and 25 + 'A'
       mov  buffer,al ;buffer = random letter
       mov edx, OFFSET buffer   ;edx = address of buffer
       call WriteString    ;write string to console

   ret
   RandomString ENDP

   end main

Solution

  • You keep resetting ecx:

        l1:
            mov ecx,L ;ecx = 20   <--set ecx to 20
            call RandomString   
            dec ecx   ;ecx --     <--ecx is now 19
            cmp ecx,0 ;compare ecx to zero
            jne l1                <-- jump to l1, and ecx becomes 20 again
    

    You should move the mov to BEFORE the l1 label:

            mov ecx,L ;ecx = 20
        l1:
            call RandomString   ;call Random String
            dec ecx   ;ecx --
            cmp ecx,0 ;compare ecx to zero
            jne l1