Page 88 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 88
Unit 6: Operations on Arrays and Sparse Matrices
A common way of representing non-zero elements of a sparse matrix is the 3-tuple form. The Notes
first row of sparse matrix always specifies the number of rows, number of columns and number
of non-zero elements in the matrix. In the example given above, the number 7 represents the
total number of rows sparse matrix. Similarly, the number 6 represents the total number of
columns in the matrix. The number 8 represents the total number of non-zero elements in the
nd
st
matrix. Each non-zero element is stored from the second row, with the 1 and 2 elements of the
row, indicating the row number and columnnumber respectively in which the element is present
in the original matrix. The 3rd element in this row stores the actual value of the non-zero
element.
Example: the 3-tuple representation of the matrix of Figure 6.2 is shown in Figure 6.3.
Figure 6.3: 3-tuple representation of Figure 6.2
The following program accepts a matrix as input, which is sparse and prints the corresponding
3-tuple representations.
The following program accepts a matrix as input and prints the 3-tuple representation of it.
#include<stdio.h>
void main()
{
int a[5][5],rows,columns,i,j;
printf(“enter the order of the matrix. The order should be less than 5 ×
5:\n”);
scanf(“%d %d”,&rows,&columns);
printf(“Enter the elements of the matrix:\n”);
for(i=0;i<rows;i++)
for(j=0;j<columns;j++)
{ scanf(“%d”,&a[i][j]);
}
printf(“The 3-tuple representation of the matrix is:\n”);
for(i=0;i<rows;i++)
for(j=0;j<columns;j++)
{
if (a[i][j]!=0)
{
LOVELY PROFESSIONAL UNIVERSITY 81