1
$\begingroup$

I have written an assembly program to store digits in a stack. And to print the digits I have used

loop2:
mov ah,2
int 21h
sub cl,1
jnz loop2

But this would only print them in reverse order as the SP is pointing to the last element, Now, I have a very simple yet very interesting question, I was very curious to know If I were to print it in the same way it was entered, how would I do that? I could use another stack but it would be quite complicated.

$\endgroup$
1
$\begingroup$

A stack is a last-in-first-out structure. This causes the reverse order you experience. What you need is a first-in-first-out structure, i.e., a queue.

This way or another, the stack in x86 is just a region in the memory you can access directly. Instead of popping each digit, initialize BP to point at the bottom of your stack (the first digit), then print it, and then advance BP to the next digit (i.e., decrease BP since the stack grows towards lower addresses). At the end of the print loop, just clean the stack by popping everything out, or by changing SP directly.

MOV BP, SP    ; init BP to the first digit

... <push digits> , <init CX> ...

PrintLoop:
   MOV DX, [BP]
   MOV AH, 2
   INT 21h            ; print

   SUB BP, 2          ; assuming each digit is a word
   LOOP PrintLoop     ; Loop according to CX

MOV SP, <...>         ; restore stack / "pop" everything 
$\endgroup$
3
  • $\begingroup$ There is a problem I am facing using this, the program is now printing an empty character at the beginning, like instead of just printing "12345", it is printing an empty space at first like " 12345", is it a issue or does it always happen like that? $\endgroup$ – kiv Apr 21 at 10:34
  • $\begingroup$ Maybe you initialized BP to the wrong place or initialized a wrong counter and thus you are printing an extra space for some reason. $\endgroup$ – Ran G. Apr 21 at 10:36
  • $\begingroup$ yeah, i fixed this issue by decreasing the BP by 2 before the print loop, it works fine. Thanks. $\endgroup$ – kiv Apr 21 at 11:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.