Factorial in Assembly Language

Mujahid picture Mujahid · Oct 1, 2013 · Viewed 12.5k times · Source

I want to find a factorial of a number which is less than 8 using this code. but this is not working can anyone help me out? This was my home work. i tried but it is printing same character again and agian..

.model small_  
.stack_

.data_  
no db 1h_ ;  
counter db 1_  
string1 db "Please Enter the No. to calculate factorial (0~8): ","$"  
string2 db "Factorial is: ","$"  

.code  
main proc  
mov ax,@data  
mov ds,ax  
mov dx,offset string1  
mov ah,09h  
int 21h  
mov cl,1  
loop1:  
cmp counter,3  
ja End1  
mov ah,01h  
int 21h  
sub al,48  
inc counter  
mov no,al  
cmp no,8  
ja loop1  

Factorial:  
cmp no,cl  
je display  
mul al,cl  
inc cl  
jmp factorial  

Display:  
mov ax,@data  
mov ds,ax  
mov dx,offset string2  
mov ah,09  
int 21h  
mov dl,al  
add dl,48  
mov ah,02h  
int 21h  
End1:  
mov ah,4ch  
int  21h  
main endp  
**_End main _**

Answer

us2012 picture us2012 · Oct 1, 2013

You have at least three major problems in your code:

  • 8! is too large to fit into AL.
  • Your printing code only works for numbers up to 9. You're adding 48 and then printing as a character, which is fine for single-digit, but even for 10 it can't work. You need to write a complete section for printing numbers (or maybe use one that your professor provided)?
  • You are storing the result of your computation in AL, but you overwrite it when you do mov ax, @Data.