DS Unit1 Arrays
DS Unit1 Arrays
Data Structures
Dr. Nivedita Palia
• Introduction of Arrays
• An array is a fixed-size sequential collection of elements of same data type in
continuous memory location.
• The elements of an array are referenced by an index (also known as subscript).
Declaration Examples:
float height[50]; int group[10]; char name[10];
Storing values in an array
Consider the linear arrays AAA(5:50) and B(-5:10). Find the number of elements
in each array.
Memory Representation of Linear Array
Q1 Consider a linear array A[5:50]. Suppose BA(A)= 300 and w=4 words per memory
cell for array A. Find the address of A[15] and A[55].
Operations on Arrays
1. Traversing an array
2. Inserting an element in an array
3. Searching an element in an array
4. Deleting an element from an array
5. Merging two arrays
6. Sorting an array in ascending or descending order
Traversing Linear Arrays
Accessing and processing each elements of an array exactly once.
Example: Print an array, count the number of elements in an array
Declaration :
datatype name_of_array[row_size][column_size2];
int marks[3][5];
Memory Representation of 2-D Array
Initialize 2-D Array
#include<stdio.h>
int main()
{int a[5][5],b[5][5],i,j,m,n;
printf("enter the number of rows and column of the first array A");
scanf("%d%d",&m,&n);
printf("Enter the element of first array");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf(" Print an array A\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}}
3-D Arrays
Syntax:
Datatype name_of_array[size1][size2][size3];
int A[2][3][3];
Total elements = 2*3*3=18
Memory Representation
of 3-D Array
Address Calculation for
• Column major : BA+w[(E *L +E )*L +E )]
3-D array
3 2 2 1 1
• Row major: BA+w[(E1*L2+E2)*L3+ E3]
• Ei= Ki-Lbi
• Ei: Effective index
• Li: Length of I index