Mix (C++ and Assembly) Program to Find Reverse of an Array

This post explores how to reverse an array of integers using inline assembly within a C++ program. The program swaps elements from the start and end of the array using low-level assembly instructions.

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

void main()
{
    int nos[5], x, y;
    cout << "\n Enter 5 numbers:";
    int i, j;
    for(i = 0; i < 5; i++)
    {
        cin >> nos[i];
    }
    for(i = 0, j = 4; i < 3; i++, j--)
    {
        x = nos[i];
        y = nos[j];
        _asm{
            mov ax, x
            mov bx, y
            mov cx, ax
            mov ax, bx
            mov bx, cx
            mov x, ax
            mov y, bx
        }
        nos[i] = x;
        nos[j] = y;
    }
    cout << "\n Reverse:";
    for(i = 0; i < 5; i++)
    {
        cout << nos[i] << " ";
    }
    getch();
}

Understanding the Code

Variable Declarations
int nos[5], x, y; → Declares an array of 5 integers and two temporary variables for swapping.
int i, j; → Loop control variables.

User Input
The user is prompted to enter 5 integer values which are stored in the array nos.

Inline Assembly for Swapping
The loop runs from the beginning and end of the array, swapping the elements using inline assembly:

  • mov ax, x and mov bx, y → Move the values to registers.
  • mov cx, ax → Temporarily hold x in cx.
  • mov ax, bx and mov bx, cx → Swap the values.
  • mov x, ax and mov y, bx → Store swapped values back.

This logic effectively reverses the array.

Output Display
The reversed array is printed using cout.


Output

Enter 5 numbers:10
12
15
9
11
Reverse:11 9 15 12 10

Output Explanation

If you input the values 10, 12, 15, 9, 11, the reversed array will be 11, 9, 15, 12, 10. The inline assembly code efficiently handles the swapping logic for the reversal.

Leave a Reply

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