Answer to Question #129136 in C for MD RASEL BHUYAN

Question #129136
WAP in C to represent a sparse matrix in three tuple method.
1
Expert's answer
2020-08-11T10:40:23-0400
#include<cstdio>

#define srow 50
#define mrow 20
#define mcol 20


int main() {
    int mat[mrow][mcol], sparse[srow][3];
    int i, j, nzero = 0, mr, mc, sr, s;

    printf("Enter number of rows : ");
    scanf("%d", &mr);
    printf("Enter number of columns : ");
    scanf("%d", &mc);

    for (i = 0; i < mr; i++)
        for (j = 0; j < mc; j++) {
            printf("Enter element for row %d,column %d : ", i + 1, j + 1);
            scanf("%d", &mat[i][j]);
        }


    printf("Entered matrix is : \n");
    for (i = 0; i < mr; i++) {
        for (j = 0; j < mc; j++) {
            printf("%6d", mat[i][j]);
            if (mat[i][j] != 0)
                nzero++;
        }
        printf("\n");
    }

    sr = nzero + 1;
    sparse[0][0] = mr;
    sparse[0][1] = mc;
    sparse[0][2] = nzero;
    s = 1;

    for (i = 0; i < mr; i++)
        for (j = 0; j < mc; j++) {
            if (mat[i][j] != 0) {
                sparse[s][0] = i + 1;
                sparse[s][1] = j + 1;
                sparse[s][2] = mat[i][j];
                s++;
            }
        }

    printf("Sparse matrix is :\n");
    for (i = 0; i < sr; i++) {
        for (j = 0; j < 3; j++)
            printf("%5d", sparse[i][j]);
        printf("\n");
    }
}


Output:



Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS