Skip to main content

Mix (Assembly and C++) Program to Find Greatest of Two Numbers

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 the AX register.
  • mov bx, b: Loads the second number into the BX register.
  • sub ax, bx: Subtracts BX from AX.
  • js true: If the result is negative (i.e., AX < BX), it jumps to label true.
  • jmp end: Skips over the true label if AX >= BX.

Conditional Logic

  • If the result of a - b is negative, it means a < b, and the program prints that b 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”.

No Comments yet!

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