Lab#11
Two-Dimensional Arrays
After completing this lab
• Students will know how a 2D array is stored in memory.
• Students will know how a 2D array can be accessed from memory.
• Students will be able to perform various operations on the applications of 2D arrays.
Storage of 2D arrays in memory
Note that a 2D matrix is stored in a memory as a linear array as shown in the image below. You
can access this linear array using base plus index addressing mode. Base register (BX) will hold
the base address of the array, while the index address will be incremented as you access the linear
array.
Linear address calculations
linear_address = base_address + (row_index x num_columns + column_index) x element_size
For (1,2), the linear address will be calculated by the following equation. Please note that this address will
be the offset part of logical address whereas the segment part will be from DS register.
Linear_address = base_address + (1 x 3 + 2) x 1
Example#1
Program to declare and initialize 3x3 array in assembly language.
.model small
.data
array2d db 1,2,3
db 3,4,5
db 6,7,8
.code
Example#2
Program to read index (2,1) of a 2D array.
.model small
.data
array2d db 1,2,3
db 3,4,5
db 6,7,8
.code mov ax,@data
mov ds,ax
mov bx,offset array2d
mov al,3 ; number of cols
mov dl,2 ;mov row index to dl (i,j) = (2,1)
mov dh,1 ;mov column index to dh (i,j) = (2,1)
mul dl ;multiple row index with number of col
add al,dh ; add col index to the product calculated in previous instruction
mov si,ax ; moving linear address to si
mov al,[bx+si] ; reading desired element that is 7 at index (2,1)
.exit
Emu8086 Tutorial Step by Step
Step-1
Double click on the icon on the desktop
Step-2
The following window will appear. Click on new.
Step-3: Click on empty workspace and press OK.
Step-4: Type the code given in example#2 and click on emulate.
Step-5: Click on the view→memory button to view 2D array stored in memory.
Step-6: Keep clicking on “Single step” and observe the working of the program.
Practice Exercise
Task-1
Write a program that declares and initializes a 3x4-sized matrix M1, takes its transpose, and
stores the transpose in another matrix M2.
Task-2
Write a program that initializes two 3x4-size matrices and stores their sum in another matrix.
Task-3
Write a program that initializes two 3x4 and 4x3-size matrices, named A and B, and stores the
result after multiplication of A and B into a third matrix, C.