Google

Program to represent Sparse Matrix using arrays

Written on:August 20, 2012
Comments are closed

Program to represent Sparse Matrix using arrays:

/* Sparse Matrix representation using arrays */

#include <stdio.h>
#include <stdlib.h>

#define MAX 15

int main(){
int arr[3][4],i,j,m,n,nrows,ncols,ct=0;
int sparse_matrix[MAX][MAX];
for(i=0;i<3;i++){
printf(“nEnter values for row %d?”,i+1);
for(j=0;j<4;j++){
scanf(“%d”,&arr[i][j]);
if(arr[i][j] != 0)
ct++;
}
}
nrows = ct+1;
ncols = 3;
sparse_matrix[0][0] = 3;
sparse_matrix[0][1] = 4;
sparse_matrix[0][2] = ct;
m=1;
n=0;
for(i=0;i<3;i++){
for(j=0;j<4;j++){
if(arr[i][j]!=0){
sparse_matrix[m][n++]=i;
sparse_matrix[m][n++]=j;
sparse_matrix[m][n]=arr[i][j];
m++;
n=0;
}
}
}
printf(“nThe new sparse matrix in 3-tuple representation is:n”);
for(i=0;i<nrows;i++){
for(j=0;j<ncols;j++){
printf(“%dt”,sparse_matrix[i][j]);
}
printf(“n”);
}
}

Sorry, the comment form is closed at this time.