6. Program to Reverse an Array in Assembly Language using Visual Studio

Chapter 3

Assembly Language Fundamentals

Assembly Language Programming Exercise

Problem # 6:

Use a loop with indirect or indexed addressing to reverse the elements of an integer array in place. Do not copy the elements to any other array. Use the SIZEOF, TYPE, and LENGTHOF operators to make the program as flexible as possible if the array size and type should be changed in the future.

Solution:

.386
.model flat,stdcall
.stack 4096
ExitProcess PROTO, dwExitCode:DWORD

.data
decimalArray DWORD 1,2,3,4,5,6,7,8
.code
main PROC

MOV ESI, OFFSET decimalArray
MOV EDI, OFFSET decimalArray
mov ecx, LENGTHOF decimalArray-1
L1:
ADD EDI, TYPE decimalArray
LOOP L1

mov ecx, LENGTHOF decimalArray
L2:
MOV EAX, [ESI]
MOV EBX, [EDI]
XCHG EAX, EBX
MOV [ESI], EAX
MOV [EDI], EBX

ADD ESI, TYPE decimalArray
SUB EDI, TYPE decimalArray
DEC ECX

LOOP L2

INVOKE ExitProcess,0
main ENDP
END main

OR

.386
.model flat,stdcall
.stack 4096
ExitProcess PROTO, dwExitCode:DWORD

.data
decimalArray DWORD 1,2,3,4,5,6,7,8
.code
main PROC

MOV ESI, OFFSET decimalArray
MOV EDI, OFFSET decimalArray
ADD EDI, SIZEOF decimalArray
SUB EDI, TYPE decimalArray

mov ecx, LENGTHOF decimalArray
L2:
MOV EAX, [ESI]
MOV EBX, [EDI]
XCHG EAX, EBX
MOV [ESI], EAX
MOV [EDI], EBX

ADD ESI, TYPE decimalArray
SUB EDI, TYPE decimalArray
DEC ECX

LOOP L2

INVOKE ExitProcess,0
main ENDP
END main

Let me know in the comment section if you have any question.

Previous Post:
Fibonacci Numbers