Arrays
Arrays
Definition:
o Arrays are defined as the collection of similar type of data items stored at contiguous memory locations.
o Arrays are the derived data type in C programming language which can store the primitive type of data
such as int, char, double, float, etc.
o Array is the simplest data structure where each data element can be randomly accessed by using its
index number.
o For example, if we want to store the marks of a student in 6 subjects, then we don't need to define
different variable for the marks in different subject. Instead of that, we can define an array which can
store the marks in each subject at the contiguous memory locations.
The array marks[10] defines the marks of the student in 10 different subjects where each subject marks are
located at a particular subscript in the array i.e. marks[0] denotes the marks in first subject, marks[1] denotes
the marks in 2nd subject and so on.
printf(avg);
}
Advantages of Array
o Array provides the single name for the group of variables of the same type therefore, it is easy to
remember the name of all the elements of an array.
o Traversing an array is a very simple process, we just need to increment the base address of the array in
order to visit each element one by one.
o Any element in the array can be directly accessed by using the index.
In the following image, we have shown the memory allocation of an array arr of size 5. The array follows 0-
based indexing approach. The base address of the array is 100th byte. This will be the address of arr[0]. Here,
the size of int is 4 bytes therefore each element will take 4 bytes in the memory.
Address of any element of a 1D array can be calculated by using the following formula:
Byte address of element A[i] = base address + size * ( i - first index)
One-Dimensional Arrays:
A one-dimensional array is one in which only one subscript specification is needed to specify a particular
element of the array. One-dimensional array can be declared as
data-type var_name[subscript];
The expression or subscript specifies the number of values to be stored in the array. The subscript (also known
as length or size of the array) must be an integer value. The length of the array can be found by the formula
L=UB-LB+1.
Example:
a) If we declare int A[8]; 16 bytes get immediately reserved in memory, 2 bytes for each of A[0], A[1], - - -
A[7]. Let bass address is 2000. Storage class was declared to be static then all the array elements would have a
default initial value as zero.
Now address of element A[5] = 2000+(5-0)*2
= 2010
b) In an array, A[-10 ..... +2 ], Base address (BA) = 999, size of an element = 2 bytes,
find the location of A[-1].
L(A[-1]) = 999 + [(-1) - (-10)] x 2
= 999 + 18
= 1017
Operations on Array:
1. Insertion of an element in an array (including available space checking)
2. Deletion of an element from an array
3. Reverse elements of an array
4. Searching an element within an array
5. Merging two arrays.
Insertion of a new element in an array can be done in two ways if sufficient memory spaces are available:
a) Insertion at the end of array
b) Insertion at required position.
For inserting the element at required position, elements must be moved forwards to new locations to
accommodate the new element and keep the order of the elements.
Algorithm:
For inserting an element into a linear array array_insert(a, n, pos, num, ARRAY_SIZE) where a is linear array,
n be total number of elements with in array pos is the position at which number num will be inserted.
ARRAY_SIZE is the size of the array.
Data Structures & Algorithms by Dr. K Bhowal Page 4 of 18
Algorithm array_insert( a, n, pos, num, ARRAY_SIZE)
{
if(n = = ARRAY_SIZE)
{
printf(“ Array is Full, Insertion is not possible”);
return;
}
for (i=n ; i>pos ; i--)
{
a[i] = a[i-1]; //Shift the elements down by 1 position
}
set a[pos]=num; // Insert the element at required position
set n = n + 1 //Increase the number of elements by 1
return or display the new list.
}
Complexity Analysis:
Worst Case Analysis: If we want to insert an element in the first position of the list, all n-1 elements of the
array have to be shifted towards right by one position. So the worst case time complexity of array insertion is
O(n).
Average Case Analysis: If we want to insert an element in the middle position of the list, half of the elements
(n/2) of the array have to be shifted towards right by one position. So the average case time complexity of array
insertion is O(n).
Best Case Analysis: When one want to insert an element at the last position of the list, no shifting operation is
required. So the best case time complexity of array insertion is O(1).
For deletion of an element from the required position, elements must be moved upwards to overwrite the
element.
Algorithm:
For deleting an element from a linear array array_del(a, n, pos, ARRAY_SIZE) where a is linear array, n be
total number of elements with in array pos is the position at which number is to be deleted. ARRAY_SIZE is
the size of the array.
Data Structures & Algorithms by Dr. K Bhowal Page 5 of 18
Algorithm array_del( a, n, pos, ARRAY_SIZE)
{
if(n <1)
{
printf(“ Array has no element, Deletion is not possible”);
return;
}
for (i=pos ; i<n-1 ; i++)
{
a[i] = a[i+1]; //Shift the elements down by 1 position
}
set n = n - 1 //decrease the number of elements by 1
return or display the new list.
}
Complexity Analysis:
Worst Case Analysis: If we want to delete an element from the first position of the list, all n-1 elements of the
array have to be shifted towards left by one position. So the worst case time complexity of array insertion is
O(n).
Average Case Analysis: If we want to delete an element from the middle position of the list, half of the
elements (n/2) of the array have to be shifted towards left by one position. So the average case time complexity
of array insertion is O(n).
Best Case Analysis: If we want to delete an element from the last position of the list, no shifting operation is
required. So the best case time complexity of array insertion is O(1).
0 1 2 3 4 5 6 7 8 9
10 20 30 40 50 60 70 80 90 100
Reversing an array can be done in many ways. Here we described a methods which has the minimum time
complexity.
Algorithm:
For reversing elements of a linear array array_rev(a, n) where a is linear array, n be total number of elements
with in array.
Algorithm array_rev( a, n)
{
for ( i = 0 ; i < n / 2 ; i++ )
{
temp = arr[i] ;
arr[i] = arr[n - 1 - i] ; //swaping 0th and 9th position values for i=0
arr[n - 1 - i] = temp ; //swaping 1st and 8th position values for i=1
}
return or display the new list;
}
Complexity Analysis:
In all cases the loop will iterate n/2 number of times. So in Worst Case, Average Case and Best Case time
complexity of array reverse is O(n).
Algorithm:
For searching an element from a linear array array_search(a, n, num) where a is linear array, n be total number
of elements with in array and num is the number to be searched.
Algorithm:
For merging two arrays array_merge(a, b, c, an, bn) where a, b, c are linear arrays, an , bn are total number of
elements of array a, b respectively.
Programs:
/* Program to implement array operations */
#include <stdio.h>
#include <conio.h>
#define MAX 10
#define MAX1 10
#define MAX2 10
void array_insert ( int [], int pos, int num) ;
void array_del ( int [], int pos ) ;
void array_rev ( int []) ;
void array_display ( int []) ;
void marray_display(int *);
void array_search ( int [], int num ) ;
void array_sort(int *,int);
int *array_merge(int *, int *);
int n=0;
int an,bn;
void main( )
{
int a[MAX],A[MAX1],B[MAX2],*C,x,pos,num,i;
while(1)
{
printf("\n Press 1 to insert new element
\n Press 2 to delete an element");
printf("\n Press 3 to reverse an array
\n Press 4 to search an element");
printf("\n Press 5 to merge two arrays\n Press 6 to display array");
printf("\n Press 7 to exit");
scanf("%d",&x);
switch(x)
{
case 1: printf("\n Enter position and new element");
scanf("%d%d",&pos,&num);
array_insert(a,pos,num);
break;
case 2: printf("\n Enter position");
scanf("%d",&pos);
array_del(a,pos);
break;
case 3: array_rev(a);
break;
case 4: printf("\n Enter an element to search");
scanf("%d",&num);
array_search(a,num);
break;
case 5: printf("\n Enter how many numbers for matrix 1:");
scanf("%d",&an);
printf("\n Enter element for matrix 1:");
for( i=0;i<an;i++)
scanf("%d",&A[i]);
printf("\n Enter how many numbers for matrix 2:");
scanf("%d",&bn);
printf("\n Enter element for matrix 2:");
for( i=0;i<bn;i++)
scanf("%d",&B[i]);
array_sort(A,an);
case 6: array_display(a);
break;
case 7: exit(0);
}
}
}
arr[pos] = num ;
n=n+1;
}
Memory Representation:
Two dimensional array is also called a matrix. If we declare int A[4] [2];
16 bytes get immediately reserved in memory, 2 bytes for each of A[0] [0], A[0] [1], A[1] [0], A[1] [1] , A[2]
[0], A[2] [1], A[3] [0], A[3] [1].
A[0] [0] A[0] [1] A[1] [0] A[1] [1] A[2] [0] A[2] [1] A[3] [0] A[3] [1]
A two dimensional array is also stored in a sequential manner in memory just like one dimensional array. To
store a two dimensional array in linear fashion, one can put the first row, followed by the second row and so on.
Alternatively, one can put the first column followed by the second column and so on.
Therefore, two dimensional arrays can be represented by two ways:
i) Row-Major Representation:
Row-Major implementation is a linearization technique in which elements of array are read from keyboard
row-wise i.e., the complete first row is stored, then the complete second row is stored and so on.
Example: Representation of a 4X3 or A[4][3] array
A00 1 4000
A01 2 4002
A02 3 4004
A10 4 4006
A11 5 4008
A12 6 4010
A20 7 4012
A21 8 4014
A22 9 4016
A30 10 4018
A31 11 4020
A32 12 4022
Row-Major Representation
The computer does not keep the track of all elements of the array, it keeps a base address ( i.e., the address
Data Structures & Algorithms by Dr. K Bhowal Page 11 of 18
of the first element in the array), and calculates the address of required element when needed.
If base address is 4000 and size of each element is 2 bytes, then address of A[2][1] or A21 = 4000 + [(2-0)*(3-0)
+ ( 1-0)]*2
= 4000 + 14 =4014 [see figure]
If array is A[4:7, -1:3], base address 4000, size of each element is 2 bytes, then address of A[6,2] = 4000 + [(6-
4)*(3 – (-1) +1) +(2-(-1))]*2 = 4026
In Column-Major Representation,
Address of a[i][j] = BA + number of elements before a[i][j] * size of each element
= BaseAddr + [ (j – lb2)*nr + (i – lb1)]*SIZE
Where number of rows, nr = (ub1 –lb1) or nr = (ub1 –lb1 + 1)
If base address is 4000 and size of each element is 2 bytes, then address of A[2][1] or A21
= 4000 + [(1-0)*(4-0) + ( 2-0)]*2 = 4000 + 12 =4012 [see figure]
Data Structures & Algorithms by Dr. K Bhowal Page 12 of 18
If array is A[-20:20, 10:35], base address 4000, size of each element is 2 bytes, then
address of A[0,30] = 4000 + [(30-10)*(20 – (-20) +1) +(0-(-20))]*2 = 41680
Sparse Matrix
A matrix is said to be sparse if many of its elements are zero i.e., zeros as the dominating elements. A matrix is
not sparse is called dense matrix. There is no precise definition for a sparse matrix. In other words, the
sparseness is relatively defined.
If majority of elements of the matrix are zero then to save valuable storage space, we can use triple
representation (row, col, element) to represent each non-zero element of the sparse matrix. Here first field of the
triplet is used to record row position, second to record column position, and the third one to record the nonzero
element of the sparse matrix.
In addition, we need to record the size of the matrix and nonzero elements. For this purpose, the first element of
array of triplets is used for this purpose, where first field stores number of rows, the second field stores number
of column and third field stores number of nonzero elements. The remaining elements of the array store nonzero
elements of the sparse matrix on row-major order.
The array representation will use [2*(n+1)*sizeof(int) + n*sizeof(T)] bytes of memory, where n is the number of
nonzero elements and T is the data type of elements.
Program to represent sparse matrix, transpose a sparse matrix, add two sparse matrices:
//Sparse Matrix operations
#include<stdio.h>
#include<conio.h>
int main()
{
stype sp1[10],sp2[10],sp3[20];
int p1,p2;
printf("\n Enter data for matrix 1:\n");
create_sparse(sp1,&p1);
printf("\n The matrix 1=\n");
display(sp1,p1);
printf("\n Enter data for matrix 2:\n");
create_sparse(sp2,&p2);
printf("\n The matrix 2=\n");
display(sp2,p2);
add_sparse(sp1,p1,sp2,p2);
transpose_sparse(sp1,p1);
printf("\n The transpose of matrix 1 is:\n");
display(sp1,p1);
return 0;
}
void create_sparse(stype sp[], int *p)
{
int i,j,k=0,nor,noc,x;
printf("\n Enter number of rows, cols & non-zero values:");
scanf("%d%d%d",&nor,&noc,&sp[k].value);
sp[k].row=nor;
sp[k].col=noc;
k++;
printf("\n Enter elements one by one:");
for(i=0;i<nor;i++)
{
for(j=0;j<noc;j++)
{
scanf("%d",&x);
if(x!=0)
{
sp[k].row=i;
sp[k].col=j;
sp[k].value=x;
k++;
}
}
void add_sparse( stype sp1[], int p1, stype sp2[], int p2)
{
int i,j,k=1,flag=0;
stype sp3[20];
if(sp1[0].row!=sp2[0].row || sp1[0].col!=sp2[0].col)
{
printf("\n Addition is not possible");
return;
}
sp3[0].row=sp1[0].row;
sp3[0].col=sp1[0].col;
for(i=1;i<p1;i++)
{
flag=0;
for(j=1;j<p2;j++)
{
if(sp1[i].row==sp2[j].row && sp1[i].col==sp2[j].col)
{
sp3[k].row=sp1[i].row;
sp3[k].col=sp1[i].col;
sp3[k].value=sp1[i].value+sp2[j].value;
k++;
flag=1;
break;
}
}
if(flag==0)
{
sp3[k].row=sp1[i].row;
sp3[k].col=sp1[i].col;
sp3[k].value=sp1[i].value;
k++;
}
}
for(j=1;j<p2;j++)
{
flag=0;
for(i=1;i<p1;i++)
{
if(sp1[i].row==sp2[j].row && sp1[i].col==sp2[j].col)
{
flag=1;
break;
}
}
if(flag==0)
{
sp3[k].row=sp2[j].row;
sp3[k].col=sp2[j].col;
sp3[k].value=sp2[j].value;
k++;
}
}
sp3[0].value=k-1;
printf("\n The resultant matrix is=\n");
display(sp3,k);
}
Data Structures & Algorithms by Dr. K Bhowal Page 15 of 18
void display(stype sp[], int n)
{
int i;
for(i=0;i<n;i++)
printf("\n%d\t%d\t%d",sp[i].row, sp[i].col, sp[i].value);
}
0 1 2 3 4 5
0 0 0 0 2 0 0
1 0 0 3 0 0 7
2 0 2 0 0 0 0
3 0 0 0 0 0 0
4 0 0 0 0 9 0
A 5X6 Sparse Matrix
void main( )
{
ptype poly1[10],poly2[10] ;
int p1,p2;
clrscr( ) ;
printf("\n Enter data for polynomial 1:\n");
create_poly(poly1,&p1);
printf ( "\nFirst polynomial:\n" ) ;
display ( poly1,p1 ) ;
printf("\n Enter data for polynomial 2:");
create_poly(poly2,&p2);
printf ( "\n\nSecond polynomial:\n" ) ;
display ( poly2,p2 ) ;
add_poly(poly1,p1,poly2,p2);
getch( ) ;
}
}
/* adds two polynomials poly1 and poly2 */
void add_poly ( ptype poly1[],int p1, ptype poly2[],int p2 )
{
int i=0, j=0,k=0;
ptype poly3[20];
while(i<p1 && j<p2)
{
if ( poly1[i].exp == poly2[j].exp )
{
poly3[k].coef = poly1[i].coef + poly2[j].coef;
poly3[k].exp = poly1[i].exp ;
i++ ;
j++ ;
k++;
}
else if(poly1[i].exp>poly2[j].exp)
{
poly3[k].coef = poly1[i].coef;
poly3[k].exp = poly1[i].exp ;
i++ ;
k++;
}
else
{
poly3[k].coef = poly2[j].coef;
poly3[k].exp = poly2[j].exp ;
j++ ;
k++;
}
}
while(i<p1)
{
poly3[k].coef = poly1[i].coef;
poly3[k].exp = poly1[i].exp ;
i++ ;
k++;
}
while(j<p2)
{
poly3[k].coef = poly2[j].coef;
poly3[k].exp = poly2[j].exp ;
j++ ;
k++;
}
printf("\n The resultant polynomial=\n");
display(poly3,k);
}