4 MultiDimensional Arrays
4 MultiDimensional Arrays
Data Structures
(1, 4)
(2, 1)
(2, 2)
(2, 3) Row 2
(2, 4)
(3, 1)
(3, 2)
(3, 3) Row 3
(3, 4)
Formula for Location of Element(1-D Array)
Address of A[I] = B + W * (I – LB)
I = Subset of element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LB = Lower Limit/Lower Bound of subscript(If not specified assume zero).
Example: Given the base address of an array A[1300 ………… 1900] as 1020 and the size of
each element is 2 bytes in the memory, find the address of A[1700].
Solution:
Given:
Base address B = 1020
Lower Limit/Lower Bound of subscript LB = 1300
Storage size of one element store in any array W = 2 Byte
Subset of element whose address to be found I = 1700
Solution:
Address of A[1700] = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * (400)
= 1020 + 800
Address of A[1700] = 1820
Formula for Location of Element(2-D Array)
If the array elements are stored in column major order,
Address(A[I][J]) = Base_Address + w{M ( J – 1) + (I – 1)}
Solution:
Address(A[I][J]) = Base_Address + w{N (I – 1) + (J – 1)}
Address(marks[18][4]) = 1000 + 2 {5(18 – 1) + (4 – 1)}
= 1000 + 2 {5(17) + 3}
= 1000 + 2 (88)
= 1000 + 176 = 1176
Program(2-D Array)
#include<stdio.h>
#include<conio.h>
int main() { int arr[10][10], row, col, i, j;
printf("Enter Row Size of Array (max. 10): ");
scanf("%d", &row);
printf("Enter Column Size of Array (max. 10): ");
scanf("%d", &col); printf("\nEnter %d Array Elements: ", row*col);
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
scanf("%d", &arr[i][j]);
}
printf("\nThe Array is:\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
getch();
return 0;
}
Program(2-D Array-Strings)
#include<stdio.h>
#include<string.h> printf("\nEnter Name to be Searched: ");
int main() scanf("%s",search);
{ for(i=0;i<n;i++)
char data[100][100],search[50]; {
int i,n,c=0; if(strcmp(data[i],search)==0)
printf("/How Many Names You Want \nto {
Add in 2-D Array/\n\nEnter Limit: "); c=1;
scanf("%d",&n); break;
printf("------------------------------------\n"); }
for(i=0;i<n;i++) }
{ if(c==1)
printf("Enter Name-%d = ",i+1); printf("\n%s Found at Position
scanf("%s",data[i]); '%d'",data[i],i+1);
} else
printf("\nElement Present in 2-D Array are:\ printf("\n%s NOT Present in Above
n"); Array",data[i]);
printf("------------------------------------\n"); return 0;
for(i=0;i<n;i++) }
{
printf("\t%s\n",data[i]);
}
Program(Array-Strings)
#include <stdio.h>
#include <string.h>
int main()
{
char s1[1000],s2[1000];
int i,j;
printf("Enter string1: ");
gets(s1);
printf("Enter string2: ");
gets(s2);
j=strlen(s1);
for(i=0;s2[i]!='\0';i++)
{
s1[i+j]=s2[i];
}
s1[i+j]='\0';
printf("combined two strings ='%s'\n",s1);
return 0;
}
Column-Major Order:
LOC (A[j, k]) = Base (A) + w [M (k-1) + (j-1)]
Row-Major Order:
LOC (A[j, k]) = Base (A) + w [N (j-1) + (k-1)]