Riphah International University
Computer Organization and Assembly Language
We shall cover following programs in this manual.
• Applications of stack
• Swapping two number, reverse a string, pattern print using nested loop,
• Practice questions
Use of stack:
Stack is data structure where LIFO criteria is involved. Stack is used in many functions. Two different
registers Stack Point Register and Stack Segment Register, SPR points the top of stack while SSR holds
the address of space reserved for stack. Stack is used in many different functions, such as solving
mathematical problems, undo/redo and back/ forward and swapping functions.
To implement logic
Example: swapping two numbers using stack
;program to swap two numbers
dosseg
.model small
.stack 100h
.data
.code
main proc
mov ax, '1' ; mov 1 to register ax
push ax
mov bx,'2'
push bx
pop ax;
pop bx;
mov ah,4ch
int 21h
main endp
end main
Reverse a string.:
To reverse a string just push all the letters of string into stack and then pop them, it will automatically
reverse the string, refer to the following code.
Example code
;program to reverse
dosseg
.model small
1
.data
string db 'ahmed$'
.code
main proc
mov ax, @data
mov ds, ax
mov si, offset string
mov cx,5
psh:
mov bx, [si]
push bx
inc si
loop psh
mov cx,5
pp:
pop dx
mov ah,2
int 21h
loop pp
mov ah,4ch
int 21h
main endp
end main
nested loop:
Loop inside a loop is called nested loop. We can implement idea of nested loop in Assembly language.
There are many uses of nested loop, to print data in table form or to perform operations on matrix or to
print star patterns. In all these cases nested loop is very handy.
The syntax and structure of loop remain same, we just need to put cx value (cx is counter loop that
hands the loop) in stack in inner loop because its being used in outer loop too.
Following fig describes this with an example.
We push cx value (which is 4
at this time) to reserve it
Here we new value is
assigned to cx to run l2 loop
3 times
Gives back value (which is 4)
from stack to cx. So that
main loop can run 4 times
2
Example
;program to print star patterns……… (*)
;*
;**
;***
dosseg
.model small
.stack 100h
.data
.code
main proc
;mov ax,@data
;mov ds,ax
mov bx, 1
mov cx, 5
L1:
push cx
mov cx, bx
L2:
Mov dl,’*’ ; or you can pass value as ac ascii without quotes
mov ah,2
int 21h
loop L2
mov dl,10
mov ah, 2
int 21h
mov dl,13
mov ah, 2
int 21h
Inc bx
pop cx
loop L1
mov ah,4ch
int 21h
main endp
end main
Surprise Quiz . . . . . . . . . . . . . . . . . . !!!!