Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

8086 program to reverse a string

  • Last Updated : 24 Nov, 2021

Problem: Given a string we have to reverse the string and print the reversed string. 
Examples: 
 

Input: String : "This is a sample string"
Output: gnirts elpmas a si sihT

Input: String : "Geeks for Geeks"
Output: skeeG rof skeeG 

Explanation: 
 

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

 

  1. Create a string
  2. Traverse through the string
  3. Push the characters in the stack
  4. Count the number of characters
  5. Load the starting address of the string
  6. POP the top character of the stack until count is not equal to zero
  7. Put the character and reduce the count and increase the address
  8. Continue until the count is greater than zero
  9. Load the effective address of the string in dx using LEA command
  10. Print the sting by calling the interrupt with 9H in AH
  11. The string must be terminated by ‘$’ sign

Program:
 



CPP




.MODEL SMALL
.STACK 100H
.DATA
 
; The string to be printed
STRING DB 'This is a sample string', '$'
 
.CODE
MAIN PROC FAR
MOV AX,@DATA
MOV DS,AX
 
; call reverse function
CALL REVERSE
 
; load address of the string
LEA DX,STRING
 
; output the string
; loaded in dx
MOV AH, 09H
INT 21H
 
; interrupt to exit
MOV AH, 4CH
INT 21H
 
MAIN ENDP
REVERSE PROC
    ; load the offset of
    ; the string
    MOV SI, OFFSET STRING
 
    ; count of characters of the;
    ;string
    MOV CX, 0H
 
    LOOP1:
    ; compare if this is;
    ;the last character
    MOV AX, [SI]
    CMP AL, '$'
    JE LABEL1
 
    ; else push it in the;
    ;stack
    PUSH [SI]
 
    ; increment the pointer;
    ;and count
    INC SI
    INC CX
 
    JMP LOOP1
 
    LABEL1:
    ; again load the starting;
    ;address of the string
    MOV SI, OFFSET STRING
 
        LOOP2:
        ;if count not equal to zero
        CMP CX,0
        JE EXIT
 
        ; pop the top of stack
        POP DX
 
        ; make dh, 0
        XOR DH, DH
 
        ; put the character of the;
        ;reversed string
        MOV [SI], DX
 
        ; increment si and;
        ;decrement count
        INC SI
        DEC CX
 
        JMP LOOP2
 
                 
    EXIT:
    ; add $ to the end of string
    MOV [SI],'$ '
    RET
         
REVERSE ENDP
END MAIN

Output: 
 

gnirts elpmas a si sihT

Note: 
The program cannot be run on an online editor, please use MASM to run the program and use dos box to run MASM, you might use any 8086 emulator to run the program.
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!