This C++ program calculates the factorial of a number between 0 and 8 using inline 8086 assembly instructions. The multiplication is handled within an assembly loop, showcasing a basic yet insightful use of mul
, dec
, and jnz
instructions.
#include<iostream.h>
#include<conio.h>
void main() {
clrscr();
short a;
unsigned int c;
cout << "\n Enter Number between 0 to 8:";
cin >> a;
asm mov ax, 0000h
asm mov al, 01h // Initialize AX to 1
asm mov cx, 0000h
asm mov cx, a // Set CX loop counter to input value
bac:
asm mul cx // Multiply AX by CX
asm dec cx // Decrement CX
asm jnz bac // Loop until CX reaches zero
asm mov c, ax // Move result from AX to variable c
cout << "\n Factorial of " << a << " is " << c;
getch();
}
Understanding the Code
Variable Declarations
a
→ Input value for which factorial is to be calculated.c
→ To store the final result.- Registers
AX
,CX
are used in the assembly block for arithmetic.
Assembly Instructions
mov ax, 0000h
andmov al, 01h
initialize the result in AX to 1.mov cx, a
sets the loop counter.- Inside the loop:
mul cx
multiplies AX with CX.dec cx
decrements CX.jnz bac
jumps back to labelbac
if CX is not zero.
- After the loop,
mov c, ax
stores the result into the C++ variable.
Result
- Final factorial result is printed using the value of
c
.
Output
Enter Number between 0 to 8:6
Factorial of 6 is 720
Output Explanation
The user is prompted to enter a number between 0 and 8. When 6
is entered:
- The loop begins with AX = 1.
- Then AX is multiplied successively by 6, 5, 4, 3, 2, and 1 using the
mul
instruction. - The result is stored in variable
c
which holds 720. - The final output confirms the computed factorial: “Factorial of 6 is 720.”
What changes should i do to find the factorial of a number greater than 8? Can you plz tell me