Practical No 13 MP
Practical No 13 MP
.MODEL SMALL
.STACK 100h
.DATA
msg1 DB "Factorial is: $"
result DW 1
.CODE
main PROC
MOV AX, @DATA
MOV DS, AX
MOV ES, AX
NextDigit:
MOV BL, [SI]
CMP BL, ' '
JE SkipSpace
SUB BL, '0'
MUL CX ; AX = AX * 10
ADD AX, BX ; AX += digit
SkipSpace:
INC SI
LOOP NextDigit
; AX = input number
PUSH AX
CALL Factorial
MOV result, AX
; Display message
MOV AH, 09h
LEA DX, msg1
INT 21h
; Print result
MOV AX, result
CALL PrintNumber
; Exit
MOV AH, 4Ch
INT 21h
main ENDP
; ----------------------------
; Recursive Factorial Function
; Input: number on stack
; Output: AX = factorial
; ----------------------------
Factorial PROC
PUSH BP
MOV BP, SP
DEC AX
PUSH AX ; Push (n - 1)
CALL Factorial
MOV BX, AX ; Store result of (n - 1)!
EndRecursion:
POP BP
RET
Factorial ENDP
; ----------------------------
; PrintNumber: prints number in AX
; ----------------------------
PrintNumber PROC
PUSH AX
PUSH BX
PUSH CX
PUSH DX
MOV CX, 0
MOV BX, 10
NextDigitPrint:
XOR DX, DX
DIV BX
PUSH DX
INC CX
OR AX, AX
JNZ NextDigitPrint
PrintLoop:
POP DX
ADD DL, '0'
MOV AH, 02h
INT 21h
LOOP PrintLoop
POP DX
POP CX
POP BX
POP AX
RET
PrintNumber ENDP
END main
Output:
factorial 4
Factorial is: 24