Mix (C++ and Assembly) Program to Find Whether Number is Odd or Even

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, a loads the value entered by the user into the AX register.
  • mov bx, 02h sets the divisor to 2.
  • div bx performs the division. In x86 assembly, the div instruction divides the contents of AX by the contents of BX. The quotient goes into AX, and the remainder into DX.
  • mov res, dx moves the remainder to the res variable.

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 by 2 leaves a remainder of 1, so the output is Odd.
  • For 20, the remainder is 0, so the output is Even.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.