Assembly Program to find Factorial using Recursion


This program is designed to find the factorial of a number using recursion. First of all, we have to push the number onto the stack for which we want to calculate the factorial and after pushing the number we call FIND_FACTORIAL procedure. The result will store in the FACTORIAL variable declared in the data segment.

This program will calculate the factorial of 5 as I have pushed 5 on line 7. If you want to find factorial of any other number then you have to pass that number onto the stack on line 7 instead of 5.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
ORG 100H
.DATA
FACTORIAL DB 0
.CODE
MAIN PROC
    
    PUSH 5
    CALL FIND_FACTORIAL
    RET
    
MAIN ENDP

FIND_FACTORIAL PROC
    
    MOV BP, SP
    MOV AX, [BP+2]
    
    CMP AX, 1
    JNE AGAIN
    
    MOV FACTORIAL, 1
    
    JMP EXIT 
    
    AGAIN:
    DEC AX
    PUSH AX
    CALL FIND_FACTORIAL
    
    MOV BP, SP
    MOV AX, [BP+2]
    
    MOV BL, FACTORIAL
    MUL BL
    MOV FACTORIAL, AL
    
    EXIT:
    RET 2

FIND_FACTORIAL ENDP

Output:

No comments