Advertisement
Sathvikks8

SparseMatrixTranspose.c

Oct 4th, 2020 (edited)
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.12 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #define MAX 101
  4. typedef struct{
  5.   int col;
  6.   int row;
  7.   int val;
  8. }term;
  9. term a[MAX], b[MAX];
  10. int matrix[MAX][MAX], transposeMatrix[MAX][MAX];
  11. void transpose()
  12. {
  13.   b[0].row=a[0].col;
  14.   b[0].col=a[0].row;
  15.   b[0].val=a[0].val;
  16.   int i=0, indexB=0;
  17.   while(i<a[0].col)
  18.   {
  19.     for(int j=1;j<=a[0].val;j++)
  20.     {
  21.       if(a[j].col==i)
  22.       {
  23.         b[++indexB].row=a[j].col;
  24.         b[indexB].col=a[j].row;
  25.         b[indexB].val=a[j].val;
  26.  
  27.       }
  28.     }
  29.     i++;
  30.   }
  31. }
  32. int main()
  33. {
  34.   printf("Enter the number of rows and columns of the matrix: ");
  35.     scanf("%d%d",&a[0].row,&a[0].col);
  36.   printf("\nEnter the %d elements of the matrix: ",a[0].row*a[0].col);
  37.   for(int i=0;i<a[0].row;i++)
  38.   {
  39.     for(int j=0;j<a[0].col;j++)
  40.       scanf("%d",&matrix[i][j]);
  41.   }
  42.   printf("\nThe entered sparse matrix\n");
  43.   int k=0;
  44.   a[0].val=0;
  45.   for(int i=0;i<a[0].row;i++)
  46.   {
  47.     for(int j=0;j<a[0].col;j++)
  48.     {
  49.       if(matrix[i][j]!=0)
  50.       {
  51.         a[++k].row=i;
  52.         a[k].col=j;
  53.         a[k].val=matrix[i][j];
  54.         a[0].val++;
  55.       }
  56.       printf("%d\t",matrix[i][j]);
  57.     }
  58.     printf("\n");
  59.   }
  60.   if(a[0].val==0)
  61.   {
  62.     printf("\nThe entered sparse matrix has no non-zero elements");
  63.     exit(0);
  64.   }
  65.   printf("\nThe entered sparse matrix in triplet form is\n");
  66.   printf("index\trow\tcol\tval\n");
  67.   for(int i=0;i<=(a[0].val);i++)
  68.   {
  69.     printf("a[%d]\t%d\t%d\t%d",i,a[i].row,a[i].col,a[i].val);
  70.     printf("\n");
  71.   }
  72.   transpose();
  73.   printf("\nThe transpose of the sparse matrix in triplet form is\n");
  74.   printf("index\trow\tcol\tval\n");
  75.   for(int i=0;i<=b[0].val;i++)
  76.   {
  77.     printf("b[%d]\t%d\t%d\t%d",i,b[i].row,b[i].col,b[i].val);
  78.     printf("\n");
  79.   }
  80.   for(int i=0;i<b[0].row;i++)
  81.   {
  82.     for(int j=0;j<b[0].col;j++)
  83.       transposeMatrix[i][i]=0;
  84.   }
  85.   for(int i=1;i<=b[0].val;i++)
  86.     transposeMatrix[b[i].row][b[i].col]=b[i].val;
  87.   printf("\nThe transpose of the entered sparse matrix is\n");
  88.   for(int i=0;i<b[0].row;i++)
  89.   {
  90.     for(int j=0;j<b[0].col;j++)
  91.       printf("%d\t",transposeMatrix[i][j]);
  92.     printf("\n");
  93.   }
  94. }
  95.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement