This C++ program determines whether a given number is even or odd using 8086-style inline assembly. It utilizes the div instruction to divide the number by 2 and then checks the remainder stored in the dx register.
#include<iostream.h>
#include<conio.h>
void main() {
clrscr();
int a, res;
cout << "\n Enter a number";
cin >> a;
asm mov ax, a // Move input number into AX
asm mov bx, 02h // Move divisor 2 into BX
asm div bx // Divide AX by BX, quotient in AX, remainder in DX
asm mov res, dx // Store remainder in res
if(res == 0) {
cout << "\n Even";
} else {
cout << "\n Odd";
}
getch();
}
Understanding the Code
Key Operations
mov ax, aloads the value entered by the user into the AX register.mov bx, 02hsets the divisor to 2.div bxperforms the division. In x86 assembly, thedivinstruction divides the contents of AX by the contents of BX. The quotient goes into AX, and the remainder into DX.mov res, dxmoves the remainder to theresvariable.
Logic
- If the remainder is 0 (
res == 0), then the number is divisible by 2 and is even. - Otherwise, the number is odd.
Output
Enter a number15
Odd
Enter a number20
Even
Output Explanation
When the user enters a number (e.g., 15), the program checks if it’s divisible by 2:
- For
15, the division by2leaves a remainder of1, so the output isOdd. - For
20, the remainder is0, so the output isEven.