Mix (C++ and Assembly) Program to Subtract Two 16 bit Numbers

While modern high-level languages like C++ abstract away many low-level operations, sometimes it’s useful to get closer to the hardware to understand how things work under the hood. This example demonstrates how to subtract two 16-bit numbers using inline assembly in a simple C++ program.

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

void main() {
    clrscr();

    int a, b, c;

    cout << "Enter First Number:";
    cin >> a;

    cout << "Enter Second Number:";
    cin >> b;

    asm mov ax, a      // Move 'a' into AX
    asm mov bx, b      // Move 'b' into BX
    asm sub ax, bx     // Subtract BX from AX
    asm mov c, ax      // Store result in 'c'

    cout << "Result:";
    cout << c;

    getch();
}

Understanding the Code

Variable Declarations

  • int a, b, c; → Declares three integer variables to store the two input values and the result.

User Input

  • The program prompts the user to enter two integer values, which are then stored in variables a and b.

Inline Assembly Operations

  • asm mov ax, a → Moves the value of a into register AX.
  • asm mov bx, b → Moves the value of b into register BX.
  • asm sub ax, bx → Subtracts the contents of BX from AX; result is stored in AX.
  • asm mov c, ax → Moves the result from AX into variable c.

Output Display

  • The final result stored in c is displayed to the user using cout.

Sample Output

Enter First Number: 978
Enter Second Number: 354
Result: 624

Subtraction of 354 from 978 results in 624.

Leave a Reply

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