Search code examples
loopsassemblywhile-loop

How to show a string 10 times using while loop in assembly language?


How to show string 10 times in assembly language?

Here is my code:

.model small
 .stack 100h
 .data
    msg db 'rashed   $'
 .code
 
 main proc
    
     
    mov ax,@data
    mov ds,ax
    
    lea dx,msg
    mov ah,9      ;string output
     int 21h 
    
       
      mov dx,0   ;dx counts characters
      mov ah,9   ;prepare for read
      int 21h  
      
      
       
     
      
     while_:
      cmp al,0dh     ;carriage return?
      je end_while    ;yes exit
      inc dx           ;no carriage return, increment count
      int 21h          ;read character
      jmp while_       ;loop back
      end_while:  
    exit:
    mov ah,4ch
    int 21h
    main endp
 end main

output is:

enter image description here

I want to show this string 10 times but the string subtracts? How to show that 10 times?


Solution

  • mov dx,0   ;dx counts characters
    

    To show the same text a number of times, choose a counter register different from the registers that are required to perform the output (In your case AX and DX). I suggest putting the counter in CX.

        mov  cx, 11
    while_:
        dec  cx           ;Change counter
        jz   end_while    ;Exit after 10 iterations
        mov  ah, 9
        int  21h          ;Print string
        jmp while_        ;Loop back
    end_while:
    

    Because a while-loop tests the condition first, I assigned 11 instead of 10.