Past exam question: 2082 Kartik (Back), Q5
Open in the Padhaiko appQuestion
Write an Assembly language programming in 8086 to display, find the factorial of given number. (The given number is in location 2050H).
Solution
Algorithm & Factorial Mathematical Formulation:
- Given number
Nis read from memory location2050Hinto register CX. - Factorial calculation:
- If
N = 0orN = 1,N! = 1. - For
N > 1:N! = N * (N - 1) * ... * 1. - Initialize product
AX = 1. - Decrement loop multiplying
AXbyCX(MUL CX) untilCX = 1.
- If
- Display logic:
- Convert the 16-bit binary product in
AXinto ASCII decimal digits by repeatedly dividing by 10 (DIV 10), pushing remainders onto the stack, and popping/printing them via DOSINT 21H, AH = 02H.
- Convert the 16-bit binary product in
Complete 8086 Assembly Language Program:
.MODEL SMALL
.STACK 100H
.DATA
MSG_PROMPT DB 'Factorial: $'
NEWLINE DB 0DH, 0AH, '$'
.CODE
MAIN PROC
MOV AX, @DATA
MOV DS, AX
; 1. Load the input number from location 2050H
MOV SI, 2050H
MOV AL, [SI] ; AL = input number N
MOV AH, 00H ; AX = N
MOV CX, AX ; CX = N (loop counter)
; 2. Initialize factorial accumulator AX = 1
MOV AX, 0001H
CMP CX, 0001H
JBE DISPLAY_FACT ; If N <= 1, 0! = 1, 1! = 1
FACT_LOOP:
MUL CX ; DX:AX = AX * CX
LOOP FACT_LOOP ; Decrements CX and loops until CX = 0
DISPLAY_FACT:
PUSH AX ; Save factorial result
; Display header message
LEA DX, MSG_PROMPT
MOV AH, 09H
INT 21H
POP AX ; Restore factorial result in AX
; 3. Convert AX to decimal digits and display
MOV BX, 10 ; Divisor = 10
XOR CX, CX ; CX = 0 (digit counter)
DIV_LOOP:
XOR DX, DX ; Clear DX for 16-bit division DX:AX / BX
DIV BX ; AX = Quotient, DX = Remainder
PUSH DX ; Push remainder (digit) to stack
INC CX ; Increment digit count
CMP AX, 0 ; Check if quotient is zero
JNZ DIV_LOOP
PRINT_DIGITS:
POP DX ; Pop digit from stack
ADD DL, 30H ; Convert binary digit to ASCII ('0'-'9')
MOV AH, 02H ; DOS character output service
INT 21H
LOOP PRINT_DIGITS
; 4. Terminate program
MOV AH, 4CH
INT 21H
MAIN ENDP
END MAINExecution Verification: If memory byte [2050H] = 05H (5 in decimal):
- Initial:
AX = 1,CX = 5. - Multiplication passes:
1 * 5 = 5->5 * 4 = 20->20 * 3 = 60->60 * 2 = 120->120 * 1 = 120(78H). - Decimal conversion: 120 / 10 -> Remainder 0, 12 / 10 -> Remainder 2, 1 / 10 -> Remainder 1.
- Stack pops digits in correct order:
'1','2','0'. - Screen displays:
Factorial: 120.
Answer:
The program reads N from location 2050H, initializes AX=1, computes factorial by repeated multiplication (MUL CX with LOOP), converts the 16-bit result to ASCII decimal via repeated division by 10, and outputs it to the screen.