I am trying to find Factorial of a number but a unexpected output is coming. for 5 it should be 120 but 00 is coming. please Help in the following code Sometimes it goes into infinite loop.
.model small
.stack 100h
.data
buffer db 10 dup('$')
n dw 5
.code
main proc
mov ax , @data
mov ds ,ax
mov ax , n
mov bx , offset buffer
mov cx , 1
l1 :
inc cx
mul cx
cmp cx , n
jne l1
l2 :
mov dx, 0
mov cx ,10
div cx
add dl,48
mov [bx], dl
inc bx
cmp ax, 0
jne l1
mov dx , offset buffer ; moving address to dx
mov ah,9 ; printing string
int 21h
mov ax, 4c00h
int 21h
main endp
end main
The jump at the end of your l2
loop is incorrect. You're jumping to l1
when you should be jumping to l2
.
Also, in your l1
loop you inc
and mul
before you decide whether to exit the loop. So in the case where n
is 5 you'll get 5 * 2 * 3 * 4 * 5
(which is 600).