This program demonstrates how to compare two integers using 8086 inline assembly in C++. By leveraging assembly instructions like sub
and conditional jump js
, the program determines which number is greater.
#include<iostream.h>
#include<conio.h>
void main() {
clrscr();
short a;
short b;
cout << "\n Enter First Number:";
cin >> a;
cout << "\n Enter Second Number:";
cin >> b;
asm mov ax, 0000h // Clear AX
asm mov bx, 0000h // Clear BX
asm mov ax, a // Load first number into AX
asm mov bx, b // Load second number into BX
asm sub ax, bx // Subtract BX from AX
asm js true // Jump if result is negative (AX < BX)
cout << "\n " << a << " is greater than " << b;
asm jmp end // Skip 'true' block
true:
cout << "\n " << b << " is greater than " << a;
end:
getch();
}
Understanding the Code
Key Assembly Instructions
mov ax, a
: Loads the first number into theAX
register.mov bx, b
: Loads the second number into theBX
register.sub ax, bx
: SubtractsBX
fromAX
.js true
: If the result is negative (i.e.,AX < BX
), it jumps to labeltrue
.jmp end
: Skips over thetrue
label ifAX >= BX
.
Conditional Logic
- If the result of
a - b
is negative, it meansa < b
, and the program prints thatb
is greater. - Otherwise, it prints that
a
is greater.
Output
Enter First Number:5
Enter Second Number:8
8 is greater than 5
Output Explanation
When the user enters two numbers:
- If the first number is greater, the subtraction result is positive or zero, and the program prints “a is greater than b”.
- If the second number is greater, the subtraction result is negative, and the program jumps to print “b is greater than a”.