Mix (C++ and Assembly) Program to Search an Element in an Array

This C++ program demonstrates how to search for a specific element within an array of 10 integers using 8086 assembly instructions embedded inline. The program uses the cmp and jz instructions to perform the comparison and detect a match.

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

void main()
{
    int nos[10], j, t;
    int i, p;

    cout << "\n Enter 10 numbers:";
    for (i = 0; i < 10; i++) {
        cin >> nos[i];
    }

    cout << "\n Enter number to be searched:";
    cin >> j;

    for (i = 0; i < 10; i++) {
        p = i;
        t = nos[i];
        _asm {
            mov ax, t     // Load current array element
            mov bx, j     // Load number to be searched
            cmp ax, bx    // Compare current element with target
            jz out        // If match found, jump to output
        }
    }

    cout << "\n No is not found.";
    goto end;

out:
    cout << "\n Number is found at " << p + 1 << " th position";

end:
    getch();
}

Understanding the Code

Variable Declarations

  • nos[10] → Array to hold 10 integers.
  • j → Number to search.
  • t → Temporary storage for comparison.
  • p → Index tracker to store current position.

User Input
The program accepts 10 numbers to populate the array and one number to search.

Inline Assembly Instructions

  • mov ax, t → Loads the current element of the array into register AX.
  • mov bx, j → Loads the number to be searched into register BX.
  • cmp ax, bx → Compares the current element with the number to search.
  • jz out → If the numbers are equal (zero flag is set), jumps to label out.

Search Logic If no match is found after checking all elements, the program outputs “No is not found.” and exits. If a match is found, it prints the 1-based position using the label out.


Output

Enter 10 numbers:15
20
48
32
14
5
36
84
11
37
Enter number to be searched:5
Number is found at 6 th position

Output Explanation

The program checks each number in the array against the number to be searched. When it finds a match, it prints the position (index + 1). In this case, 5 is found at position 6.

Leave a Reply

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