SPARSE MATRIX
a sparse matrix is a matrix in which most of the elements are zeroIn the below program we take a sparse matrix as an input and display another resultant matrix
eg:
| 2(0,0) 0(0,1) 0(0,2) 0(0,3) | | 4 4 4 |
| 0(1,0) 1(1,1) 0(1,2) 0(1,3) | ===> | 2 0 0 |
| 0(2,0) 0(2,1) 3(2,2) 0(2,3) | | 1 1 1 |
| 3(3,0) 0(3,1) 0(3,2) 0(3,3) | | 3 2 2 |
| 3 4 0 | (t+1) X 3
here t is the number of non zero elements
where in the first row | 4 4 4 |
total rows total columns total no of non - zero elements
from second row | 2 0 0 |
non zero its position its position in column
element in row
#include <stdio.h>
#include<conio.h>
void main()
{
int i,j,p,q,a[10][10],t=0;
// here p and q is the number of rows and columns
clrscr();
printf("Enter the order of the matrix : ");
scanf("%d%d",&p,&q);
printf("Enter the elements of the matrix : \n");
//loop for taking elements into the matrix
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&a[i][j]);
}//end for j
}//end for i
//loop for printing the matrix
for(i=0;i<p;i++)
{
printf("\n");
for(j=0;j<q;j++)
{
printf("%d\t",a[i][j]);
}//end for j
}//end for i
//loop for counting the number of non zero elements
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
if(a[i][j]!=0)
{
t++;
}//end if
}//end for j
}//end for i
//for printing first row of the matrix
printf("\n\n%d\t%d\t%d\n",p,q,t);
//for printing remaining elements of the matrix
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
if(a[i][j]!=0)
{
printf("%d\t%d\t%d\n",a[i][j],i,j);
}//end if
}//end for j
}//end for i
getch();
}