Mix (C++ and Assembly) Program to Find Whether Number is Positive or Negative

This program demonstrates how to use inline 8086 assembly in C++ to determine whether a given number is positive or negative. It’s a great way to understand how conditional branching works at the assembly level.

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

void main() {
    clrscr();
    int a;

    cout << "\n Enter a number:";
    cin >> a;

    asm mov ax, 0000h     // Clear AX
    asm mov ax, a         // Move user input into AX
    asm cmp ax, 0000h     // Compare AX with 0
    asm jl less           // Jump to 'less' if AX < 0
    asm jge greater       // Jump to 'greater' if AX >= 0

less:
    cout << "\n Number is negative";
    asm jmp end

greater:
    cout << "\n Number is positive";

end:
    getch();
}

Understanding the Code

Key Assembly Instructions

  • mov ax, a: Loads the user’s input into the AX register.
  • cmp ax, 0000h: Compares the value in AX to 0.
  • jl less: If the value is less than 0, it jumps to the label less.
  • jge greater: If the value is greater than or equal to 0, it jumps to greater.
  • jmp end: Skips the next label after executing the correct block.

Conditional Logic

  • If the number is less than 0, the message “Number is negative” is displayed.
  • If the number is 0 or greater, the message “Number is positive” is shown.

Output

Enter a number:8
Number is positive

Enter a number:-32
Number is negative

Output Explanation

When a user enters a number:

  • If the input is a positive number (e.g., 8), cmp finds it greater than 0, and the program outputs “Number is positive”.
  • If the input is a negative number (e.g., -32), cmp detects it’s less than 0, and the program outputs “Number is negative”.

Leave a Reply

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