0% found this document useful (0 votes)
15 views18 pages

Arrays

Arrays are collections of similar data types stored at contiguous memory locations, allowing for efficient access via index numbers. They are essential in programming for managing large amounts of similar data without the need for multiple variable names. Operations on arrays include insertion, deletion, and searching, each with specific time complexities, and they can be initialized at compile time or runtime.

Uploaded by

kiritoarka26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views18 pages

Arrays

Arrays are collections of similar data types stored at contiguous memory locations, allowing for efficient access via index numbers. They are essential in programming for managing large amounts of similar data without the need for multiple variable names. Operations on arrays include insertion, deletion, and searching, each with specific time complexities, and they can be initialized at compile time or runtime.

Uploaded by

kiritoarka26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Array

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.

Properties of the Array:


1. Each element is of same data type and carries a same size i.e. int = 4 bytes.
2. Elements of the array are stored at contiguous memory locations where the first element is stored at the
smallest memory location.
3. Elements of the array can be randomly accessed since we can calculate the address of each element of
the array with the given base address and the size of data element.

For example, in C language, the syntax of declaring an array is like following:


int arr[10]; char arr[10]; float arr[5]

Need of using Array


In computer programming, the most of the cases requires to store the large number of data of similar type. To
store such amount of data, we need to define a large number of variables. It would be very difficult to remember
names of all the variables while writing the programs. Instead of naming all the variables with a different name,
it is better to define an array and store all the elements into it.
Following example illustrates how array can be useful in writing code for a particular problem.
In the following example, we have marks of a student in six different subjects. The problem intends to calculate
the average of all the marks of the student.
In order to illustrate the importance of array, we have created two programs, one is without using array and
other involves the use of array to store marks.

Program without array:


#include <stdio.h>
void main ()
{
int marks_1 = 56, marks_2 = 78, marks_3 = 88, marks_4 = 76, marks_5 = 56, ma
rks_6 = 89;
float avg = (marks_1 + marks_2 + marks_3 + marks_4 + marks_5 +marks_6) / 6 ;

printf(avg);
}

Program by using array:


#include <stdio.h>
void main ()
{
Data Structures & Algorithms by Dr. K Bhowal Page 1 of 18
int marks[6] = {56,78,88,76,56,89);
int i;
float avg;
for (i=0; i<6; i++ )
{
avg = avg + marks[i];
}
printf(avg);
}

Complexity of Array operations


Time and space complexity of various array operations are described in the following table.
Time Complexity
Algorithm Average Case Worst Case
Access O(1) O(1)
Search O(n) O(n)
Insertion O(n) O(n)
Deletion O(n) O(n)
Space Complexity
In array, space complexity for worst case is O(n).

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.

Memory Allocation of the array


As we have mentioned, all the data elements of an array are stored at contiguous locations in the main memory.
The name of the array represents the base address or the address of first element in the main memory. Each
element of the array is represented by a proper indexing.
The indexing of the array can be defined in three ways.
1. 0 (zero - based indexing) : The first element of the array will be arr[0].
2. 1 (one - based indexing) : The first element of the array will be arr[1].
3. n (n - based indexing) : The first element of the array can reside at any random index number.

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.

Data Structures & Algorithms by Dr. K Bhowal Page 2 of 18


In 0 based indexing, If the size of an array is n then the maximum index number, an element can have is n-1.
However, it will be n if we use 1 based indexing.

Accessing Elements of an array


To access any random element of an array we need the following information:
1. Base Address of the array.
2. Size of an element in bytes.
3. Which type of indexing, array follows?

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.

Accessing Elements of an array:


To access any random element of an array we need the following information:
1. Base Address of the array.
2. Size of an element in bytes.
3. Which type of indexing, array follows?

An array is represented sequentially in memory as like below-


A1 BA
A2 BA+W
A3 BA+2*W
A4 BA+3*W
--
--
An BA+(n-1)*W
Here BA is Base Address, W is the size of the data type.
Hence, the address of the ith element = BA+(i-LB)*W, where LB= Lower Bound =0, in C.

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

Data Structures & Algorithms by Dr. K Bhowal Page 3 of 18


Array Initialization:
1) Compile time Array Initialization:
Array variables can be initialized in declarations by constant initializers. These initializing expressions
must be constant values. The initializers are specified within braces and separated by commas. Example:
int num[10] = { 10,20,30,40,50};
int A[] = { 1,2,3,4,5};
char word[10] = { „A‟, „O‟, „T‟, „\0‟};
If there are not enough initializers for the whole array, the remaining elements of the array are initialized
to zero. That means, num[0] through num[4] are assigned the values 10,20,30,40,50 and num[5] through
num[9] are initialized to zero.
These array declaration and initialization are performed at the time of compilation.

2) Run time Array Initialization:


An array can be initialized at the time of program execution or run time. Here, first declare an array as
like int num[10]. Now we can access an array using following syntax- array_name[index or subscript];
Example:
for( i=0;i<10;i++)
{
scanf(“%d”,&num[i]);
}

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.

1. Insertion of an element in an array (including available space checking)


Let A[10] is an array with following elements, and pos=3, n=7, newvalue=35
A[0] 10 A[0] 10
A[0] 10 A[1] 20 A[1] 20
A[1] 20 A[2] 30 A[2] 30
A[2] 30 A[3] A[3]
Position for 35 35
A[3] 40 A[4] 40 A[4] 40
A[4] 50 A[5] 50 A[5] 50
A[5] 60
A[6] 60 A[6] 60
A[6] 70 A[7] 70 A[7] 70
A[7] A[8] A[8]
A[8] A[9] A[9]
A[9]
Original Array Elements shifted downwards Array after Insertion

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).

Deletion of an element from an array:


Let A[10] is an array with following elements, and pos=3, n=7
A[0] 10 A[0] 10
A[0] 10 A[1] 20 A[1] 20
A[1] 20 A[2] 30 A[2] 30
A[2] 30 A[3] 50 A[3] 50
Position for 3
A[3] 40 A[4] 60 A[4] 60
A[4] 50 A[5] 70 A[5] 70
A[5] 60 A[6] A[6]
A[6] 70 A[7] A[7]
A[7] A[8] A[8]
A[8] A[9] A[9]
A[9]
Original Array Elements shifted upwards Array after Deletion

Deletion of an element from an array can be done in two ways:


c) Deletion from the end of array
d) Deletion at required position.

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).

Reverse elements of an array


Let A[10] is an array with following elements, n=10

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).

Searching an element within an array


Searching an element means to find out a particular element is present in a list or not. Simply we have two types
of searching methods

Data Structures & Algorithms by Dr. K Bhowal Page 6 of 18


i) Sequential or Linear Searching
ii) Binary Searching
Here we discussed only linear searching. Binary searching is discussed later in the searching and sorting chapter.

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 array_search( a, n, num)


{
for ( i = 0 ; i <n ; i++ )
{
if ( a[i] == num )
{
return i ;
}
}
if ( i == n)
printf ( "\n\nThe element %d is not present in the array.", num ) ;
}

Merging two sorted arrays:


Merging of two arrays can be done different ways. Some time two arrays are copied into third array then sort
them altogether. Another way is, at the time of copying elements are compared and placed in appropriate
position of the third array. Here first compare the first element of the first array with the first element of the
second array. Here we implemented the second approach.

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.

Algorithm array_merge( a, b, c, an, bn)


{
set ia = 0, set ib = 0, set ic = 0
while( ia <= an && ib <= bn)
{
if ( a[ ia ] >= b[ ib ] )
{
c[ ic] = b[ib]
ic = ic + 1
ib = ib + 1
}
else
{
c[ ic] = a[ia]
ic = ic + 1
ia = ia + 1
}
}
while(ia <= an)
{
c[ic] = a[ia]
ic = ic + 1
ia = ia + 1
}
while(ib <= bn)
{
c[ic] = b[ib]
ic = ic + 1
Data Structures & Algorithms by Dr. K Bhowal Page 7 of 18
ib = ib + 1
}
}

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);

Data Structures & Algorithms by Dr. K Bhowal Page 8 of 18


array_sort(B,bn);
C=array_merge(A,B);
printf("\n After merging new array is :\n");
marray_display(C);
break;

case 6: array_display(a);
break;
case 7: exit(0);
}
}
}

//inserts an element num at given position pos


void array_insert ( int *arr, int pos, int num )
{
int i;
if(n>=MAX)
{
printf("\n Sufficient memory is not available");
return;
}
/* shift elements to right */

for ( i = n ; i > pos ; i-- )


arr[i] = arr[i - 1] ;

arr[pos] = num ;
n=n+1;
}

/* deletes an element from the given position pos */


void array_del ( int *arr, int pos )
{
/* skip to the desired position */
int i ;
for ( i = pos ; i < n-1 ; i++ )
arr[i] = arr[i+1] ;
n=n-1;
}

/* reverses the entire array */


void array_rev ( int *arr )
{
int i ;
for ( i = 0 ; i < n / 2 ; i++ )
{
int temp = arr[i] ;
arr[i] = arr[n - 1 - i] ;
arr[n - 1 - i] = temp ;
}
}

/* searches array for a given element num */


void array_search ( int *arr, int num )
{
/* Traverse the array */
int i ;
for ( i = 0 ; i < n ; i++ )
{
if ( arr[i] == num )
{
Data Structures & Algorithms by Dr. K Bhowal Page 9 of 18
printf ( "\n\nThe element %d is present at %dth position.", num,
i + 1 ) ;
return ;
}
}
if ( i == n )
printf ( "\n\nThe element %d is not present in the array.", num ) ;
}

/* displays the contents of a array */


void array_display ( int *arr )
{
int i ;
printf ( "\n" ) ;
for ( i = 0 ; i < n ; i++ )
printf ( "%d\t", arr[i] ) ;
}
/* displays the contents of a array */
void marray_display ( int *arr )
{
int i ;
printf ( "\n" ) ;
for ( i = 0 ; i < an+bn ; i++ )
printf ( "%d\t", arr[i] ) ;
}

/* sorts array in ascending order */


void array_sort ( int *arr, int size )
{
int i, temp, j ;
for ( i = 0 ; i < size ; i++ )
{
for ( j = 0 ; j < size-i-1 ; j++ )
{
if ( arr[j] > arr[j+1] )
{
temp = arr[j] ;
arr[j] = arr[j+1] ;
arr[j+1] = temp ;
}
}
}
}

/* merges two arrays of different size */


int* array_merge ( int *a, int *b)
{
int *arr ;
int i, k, j ;
int size = an + bn ;
arr = ( int * ) malloc ( sizeof ( int ) * ( size ) ) ;
for ( k = 0, j = 0, i = 0 ; i <= size ; i++ )
{
if ( a[k] < b[j] )
{
arr[i] = a[k] ;
k++ ;
if ( k >= an )
{
for ( i++ ; j < bn ; j++, i++ )
arr[i] = b[j] ;
}
Data Structures & Algorithms by Dr. K Bhowal Page 10 of 18
}
else
{
arr[i] = b[j] ;
j++ ;
if ( j >= bn )
{
for ( i++ ; k < an ; k++, i++ )
arr[i] = a[k] ;
}
}
}
return arr ;
}

Two Dimensional arrays:


Let A[lb1:ub1, lb2:ub2] be a two dimensional array. If every index of an array is a 2-tuple, then the array is called
a two dimensional array. Every two dimensional array has two lower bounds lb 1, lb2 and two upper bounds ub1
and ub2.
A[lb1:ub1, lb2:ub2] has a size of (ub1 – lb1+1)*(ub2 – lb2 +1). Number of element of A[-1:2, 2:6] = (2 - -1 +1)*(6
– 2 +1) = 4*5

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.

The address is calculated according to the following formula:


Address of a[i][j] = BA + number of elements before a[i][j] * size of each element.
= BaseAddr + [ (i – lb1)*nc + (j – lb2)]*SIZE.
where number of columns, nc = (ub2 –lb2) or nc = (ub2 –lb2 + 1)

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

ii) Column-Major Representation:


In Column-Major implementation memory allocation is done column by column i.e., first the element of the
complete first column is stored, then element of complete second column is stored, and so on.
Example: Representation of a 4X3 or A[4][3] array
A00 1 4000
A10 2 4002
A20 3 4004
A30 4 4006
A01 5 4008
A11 6 4010
A21 7 4012
A31 8 4014
A02 9 4016
A12 10 4018
A22 11 4020
A32 12 4022
Column-Major Representation

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

Some Matrix related Problem solving:


1) Addition of two matrices
2) Multiplication of two matrices
3) Transpose of a matrix
4) Saddle point detection of a matrix
5) Checking whether a matrix is
i) Upper triangular matrix or not
ii) Lower triangular matrix or not
iii) Diagonal matrix or not
iv) Identity matrix or not
v) Symmetric matrix or not
6) Determinant of a matrix

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.

0 1 2 3 4 5 Row Col Value


0 0 0 0 2 0 0 5 6 5
1 0 0 3 0 0 7 0 3 2
2 0 2 0 0 0 0 1 2 3
3 0 0 0 0 0 0 1 5 7
4 0 0 0 0 9 0 2 1 2
A 5X6 Sparse Matrix 4 4 9
Triplet representation of sparse matrix.

Sparse matrix can be represented using


i) Array
ii) Linked List

Sparse matrix representation using Array:


Required memory declaration for the array representation will be
struct sparse_matrix
{
int row;
int col;
float value;
};

Data Structures & Algorithms by Dr. K Bhowal Page 13 of 18


struct sparse_matrix SM[10];

Program to represent sparse matrix, transpose a sparse matrix, add two sparse matrices:
//Sparse Matrix operations
#include<stdio.h>
#include<conio.h>

typedef struct sparse


{
int row;
int col;
int value;
}stype;

void create_sparse(stype [],int *);


void add_sparse(stype [], int, stype [],int);
void transpose_sparse(stype [], int);
void display(stype [], int);

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++;
}
}

Data Structures & Algorithms by Dr. K Bhowal Page 14 of 18


}
*p=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);
}

void transpose_sparse(stype sp[], int p)


{
int i,t;
for(i=0;i<p;i++)
{
t=sp[i].row;
sp[i].row=sp[i].col;
sp[i].col=t;
}
}

Sparse matrix representation using Linked List:


The node structure for the linked representation of the sparse matrix is shown below:
ROW COL VALUE RIGHT
DOWN
Each nonzero element of the matrix is represented using the node structure. Here ROW, COL, and VALUE
fields record the row, column and value of the nonzero element in the matrix. The RIGHT link points to the
node holding the next nonzero value in the same row of the matrix. DOWN link points to the node holding the
next nonzero value in the same column of the matrix.

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

Linked List representation of a Sparse Matrix

Data Structures & Algorithms by Dr. K Bhowal Page 16 of 18


The head nodes of the row lists have their COL fields to be zero and the head nodes of the column lists have
their ROW fields to be zero. The head node of all head nodes, indicated by start, stores the dimension of the
original matrix in its ROW, COL fields.

Polynomial Representation using Array


A polynomial can be represented using array. Here, we have to store two information, coefficient value and
exponent value. Suppose we have a polynomial as like below

6x7 + 9x5 -5x3 + 2x2 + 10x + 20


So the array representation of the given polynomial looks like
Exponent 0 1 2 3 4 5 6 7
Coefficient 20 10 2 -5 0 9 0 6

//Representation, addition of two polynomial using array:


#include <stdio.h>
#include <conio.h>
#define MAX 10

typedef struct poly


{
int coef;
int exp;
}ptype;

void create_poly ( ptype [], int* ) ;


void add_poly ( ptype [], int, ptype [], int) ;
void display ( ptype [], int ) ;

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 the term of polynomial to the array t */


void create_poly ( ptype poly[], int *p )
{ int i=0;
char ch;
while(1)
{
printf("\n Enter coefficient & power:");
scanf("%d%d",&poly[i].coef,&poly[i].exp);
i++;
printf("\n Another term(y/n)?");
ch=getch();
if(ch=='n' || ch=='N')
{
break;
}
Data Structures & Algorithms by Dr. K Bhowal Page 17 of 18
}
*p=i;
}

/* displays the polynomial equation */


void display ( ptype poly[], int p )
{
int i ;
for ( i = 0 ; i < p ; i++ )
{
printf ( "%d x^%d + ", poly[i].coef, poly[i].exp ) ;
}

}
/* 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);
}

Data Structures & Algorithms by Dr. K Bhowal Page 18 of 18

You might also like