Wednesday, August 28, 2013

A Simple code to accept and display Sparse Matrix

/*
Accept and display Sparse Matrix
Sparse Matrix is the one which is created in place of conventional matrix so the space or memory consumption reduces. It actually neglects or removes the larger number of data present in a simple matrix which is repeated (In case of the below program, I considered this element as '0').

IF U GOT ANY PROBLEM WITH CODING OR THEORY, PUT IT IN COMMENTS
*/

// This code will work on Linux OS (say Ubuntu) only
// Here I took 0 as a maximum repeated value
#include<stdio.h> // preprocessor
#include<stdlib.h> // preprocessor
int r,c1; // took them as global so that it doesn't crate any problem

void accept(int a1[10][10]) // accept function
{
     int i,j;
     printf("Enter the Rows and Columns of matrix\n");
     scanf("%d%d",&r,&c1); // size of rows and columns accepted
     printf("Enter the element\n");
     for (i=0;i<r;i++)
     {
for (j=0;j<c1;j++)
{
    scanf("%d",&a1[i][j]);
}
     }
}

void display(int a1[10][10],int r,int c) // function to display both sparse and conventional matrix
{
     int i,j;
     printf("The matrix is\n");
     for (i=0;i<r;i++)
     {
for (j=0;j<c;j++)
{
    printf("%d\t",a1[i][j]);
}
printf("\n");
     }
}

void convert (int a[10][10],int b[10][10],int r,int c) // to convert conventional to sparse
{
     int i,j,k=1;
     for(i=0;i<r;i++) // goes through rows
{
for(j=0;j<c;j++) // goes through columns
{
if(a[i][j]!=0) // checks whether non zero elements are present
{
b[k][0]=i;
b[k][1]=j;
b[k][2]=a[i][j];
k++;
}
}
}
b[0][0]=r;
b[0][1]=c;
b[0][2]=k-1;
}

int main()
{
system("clear");
     int a[10][10], b[10][10], ch;
     while(1) // I wrote this program so that it runs continuously
     {
    printf("\n\tEnter the choice\n");
    printf("1. accept conventional matrix\n");
    printf("2. convert to sparse matrix\n");
      printf("3. Exit\n");
    scanf("%d",&ch);
    switch(ch)
    {
      case 1:
           accept(a);
           display(a,r,c1);
           break;
      case 2:
           convert (a,b,r,c1);
           display(b,b[0][2]+1,3);
           break;
      default:
           exit(0);
    }
     }
}

No comments:

Post a Comment