Factorial of a number - Assembly Language - MASM

Program:
.model small
.stack 200H
.data
 msg1 DB 10,13,'Enter the number:$'
 msg2 DB 10,13,'Factorial=$'
 newline DB '$' 
.code
print MACRO msg                ;macro definition
        PUSH AX
        PUSH DX
        MOV AH,09H
        MOV DX,offset msg
        INT 21H
        POP DX
        POP AX
        ENDM
.startup
       print msg1
       print newline
       CALL readnumtoAX
       mov cx,ax
       mov ax,01
ack1:    mul cx
    dec cx
    jz done
    jmp ack1
    print newline
done:
    print msg2
     call displayAX
    .exit
 readnumtoAX PROC NEAR        ;Procedure def. for reading char to ax reg.   
      PUSH BX
        PUSH CX
        MOV CX,10
        MOV BX,00
 back:  MOV AH,01H
        INT 21H
        CMP AL,'0'
        JB skip
        CMP AL,'9'
        JA skip
        SUB AL,'0'
        PUSH AX
        MOV AX,BX
        MUL CX
        MOV BX,AX
        POP AX
        MOV AH,00
        ADD BX,AX
        JMP back
     skip:
         MOV AX,BX
         POP CX
         POP BX
         RET
      readnumtoAX ENDP
displayAX PROC NEAR    ;Procedure def. to display  char in ax reg.
     PUSH DX
     PUSH CX
     PUSH BX
     PUSH AX
        MOV CX,0
        MOV BX,10
back1:        MOV DX,0
        DIV BX
        PUSH DX
        INC CX
        OR AX,AX
        JNZ back1
back2:
        POP DX
        ADD DL,30H
        MOV AH,02H
        INT 21H
        LOOP back2
        POP AX
        POP BX
        POP CX
        POP DX
        RET
displayAX ENDP

END

Output:

F:\hwlab>edit fact.asm
F:\hwlab>masm fact.asm
F:\hwlab>link fact.obj
F:\hwlab>fact

Enter the number:5
Factorial=120
F:\hwlab>fact

Enter the number:4
Factorial=24

2 comments:

  1. when i calculate the zero factorial it will give me a zero answer for the given source code but the actual answer of zero factorial is one so this source code is not working properly. Thanks

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete

Related Posts Plugin for WordPress, Blogger...