Wednesday 20 August 2014

Filled Under:

C Program to implement Sparse Matrix

Share
A matrix in which number of zero entries are much higher than the number of non zero entries is called sparse matrix. The natural method of representing matrices in memory as two-dimensional arrays may not be suitable foe sparse matrices. One may save space by storing for only non zero entries. For example matrix A (4*4 matrix) represented below where first row represent the dimension of matrix and last column tells the number of non zero values; second row on wards it is giving the position and value of non zero number.

Code:
0 0 0 15
0 0 0 0
0 9 0 0
0 0 4 0
Here the memory required is 16 elements X 2 bytes = 32 bytes
The above matrix can be written in sparse matrix form as follows:
Code:
4 4 3
0 3 15
2 1 9
3 2 4
Here the memory required is 12elements X 2 bytes = 24 bytes

Example of C Program to implement Sparse Matrix

#include<stdio.h>
#include<conio.h>

void main()
{
  int A[10][10],B[10][3],m,n,s=0,i,j;
  clrscr();
  printf("nEnter the order m x n of the sparse matrixn");
  scanf("%d%d",&m,&n);
  printf("nEnter the elements in the sparse matrix(mostly zeroes)n");
  for(i=0;i<m;i++)
  {
  for(j=0;j<n;j++)
  {
     printf("n%d row and %d column:   ",i,j);
     scanf("%d",&A[i][j]);
  }
  }
  printf("The given matrix is:n");
  for(i=0;i<m;i++)
  {
  for(j=0;j<n;j++)
  {
   printf("%d ",A[i][j]);
  }
  printf("n");
  }
  for(i=0;i<m;i++)
  {
  for(j=0;j<n;j++)
  {
   if(A[i][j]!=0)
   {
    B[s][0]=A[i][j];
    B[s][1]=i;
    B[s][2]=j;
    s++;
   }
  }
 }
  printf("nThe sparse matrix is given by");
  printf("n");
  for(i=0;i<s;i++)
  {
  for(j=0;j<3;j++)
  {
   printf("%d ",B[i][j]);
  }
  printf("n");
 }
 getch();
}