Search code examples
loopsassemblymasm

Assembler MASM, printing in JNZ loop when value is 0 or below


I'v got a a task to write a program which would create below as output:

ABCD******
   ABCD***
      ABCD

My code is:

kod segment
org 100h
assume cs:kod

start:
mov cx,3
mov bx,3
mov ax,6

mov ah, 02h

    PETLA_ZEW:

    push cx
    mov cx,4
    mov dl, 'A'

        PETLA_CIAG:

            int 21h
            inc dl
            dec cx

        jnz PETLA_CIAG

    push ax
    mov cx, ax
    mov dl, '*'

        PETLA_GWIAZD:

            int 21h
            dec cx

        jnz PETLA_GWIAZD

    sub ax, 3

    mov dl, 0ah
    int 21h
    mov dl, 0dh
    int 21h

    push bx
    mov cx, bx
    mov dl, ' '
        PETLA_SPACJE:

            int 21h
            dec bx

        jnz PETLA_SPACJE

    pop bx
    add bx, 3

    pop cx
    dec cx

    jnz PETLA_ZEW

koniec:
    mov ah, 4ch
    int 21h
kod ends
end start

but the problem is that in loop called PETLA_GWIAZD when I subtract ax 2nd time it's value is 0, which is causing the infinite loop. Is there any other loop I should use when subtracting? Maybe some validation check just before the loop? I just started working with Assembly and still do not know a lot...

Thanks!


Solution

  • The problem is the registers you are using : AX and CX are used for interrupts and loops, so you can use other registers, for example, SI instead of CX and DI instead of AX :

    kod segment
    org 100h
    assume cs:kod
    
    start:
    mov si,3        ;◄■■ INSTEAD OF CX.
    mov bx,3
    mov di,6        ;◄■■ INSTEAD OF AX.
    
    mov ah, 02h
    
        PETLA_ZEW:
    
        mov cx,4
        mov dl, 'A'
    
            PETLA_CIAG:
    
                int 21h
                inc dl
                dec cx
    
            jnz PETLA_CIAG
    
        cmp di, 0   ;◄■■ IF COUNTER == 0 ...
        je  koniec  ;◄■■ ... NO MORE ASTERISKS.
    
        mov cx, di  ;◄■■
        mov dl, '*'
    
            PETLA_GWIAZD:
    
                int 21h
                dec cx
    
            jnz PETLA_GWIAZD
    
        sub di, 3        ;◄■■
    
        mov dl, 0ah
        int 21h
        mov dl, 0dh
        int 21h
    
        push bx
        mov cx, bx
        mov dl, '_'
            PETLA_SPACJE:
    
                int 21h
                dec bx
    
            jnz PETLA_SPACJE
    
        pop bx
        add bx, 3
    
        dec si       ;◄■■
        jnz PETLA_ZEW
    
    koniec:
        mov ah, 4ch
        int 21h
    kod ends
    end start