ECEN2112 : Data Structures

Here are the working codes to ECEN2112 Data Structure Lab.

Day1: Classwork

Q1. Convert the given matrix to a sparse matrix if possible.

here is the code:

//creating a sparse matrix if possible
#include<stdio.h>
#include<stdlib.h>

#define MAX 100

//main
int main ()
{
 //declaring variables
 int m,n,A[MAX][MAX],B[MAX][3];
 int i,j,k,count=0;
 //input the matrix
 printf("\nIf input Matrix is mxn, enter 'm' and then enter 'n':\n");
 scanf ("%d%d",&m,&n);
 printf("\nNow Input the Matrix\n");
 for (i=0;i<m;i++)
 {
 for(j=0;j<n;j++)
 {
 scanf("%d",&A[i][j]);
 if(A[i][j]!=0)
 {
 count++;
 }
 }
 }
 printf("\ncount=%d",count);
 //checking if sparse
 if(count>m*n/3)
 {
 printf("\nNot a sparse Matrix\n");
 return 0;
 }
 //converting to sparse
 k=1;
 for(i=0;i<m;i++)
 {
 for(j=0;j<n;j++)
 {
 if(A[i][j]!=0)
 {
 B[k][0]=i+1;
 B[k][1]=j+1;
 B[k][2]=A[i][j];
 k++;
 }
 }
 }
 B[0][0]=m;
 B[0][1]=n;
 B[0][2]=count;
 //printing the sparse matrix
 printf("\nThe resultant Sparse Matrix is:\n\n");
 for(i=0;i<=count;i++)
 {
 for(j=0;j<3;j++)
 {
 printf("\t%d",B[i][j]);
 }
 printf("\n\n");
 }
 return 0;
}

ty

Q2.WAC to add two matrices in their sparse representation

Pages:   1 2 3 4

Leave a Comment

(0 Comments)

Your e-mail address will not be published. Required fields are marked *