OneCompiler

Spa

113

#include <stdio.h>

// Define a structure for sparse matrix representation
struct element {
int row;
int col;
int val;
};

typedef struct element matrix;

// Function to copy non-zero elements of the matrix into sparse representation
void cpynz(int totalrows, int totalcols, int matrices[][50], matrix sparseA[]) {
int k = 0;
for (int i = 0; i < totalrows; i++) {
for (int j = 0; j < totalcols; j++) {
if (matrices[i][j] != 0) {
sparseA[k].row = i;
sparseA[k].col = j;
sparseA[k].val = matrices[i][j];
k++;
}
}
}
}

// Function to transpose a sparse matrix
void transpose(int totalrows, int totalcols, matrix sparseA[], matrix transp[]) {
for (int i = 0; i < totalrows; i++) {
transp[i].row = sparseA[i].col;
transp[i].col = sparseA[i].row;
transp[i].val = sparseA[i].val;
}
}

// Function to display the transpose of the sparse matrix
void display(int totalrows, matrix transp[]) {
printf("Transposed matrix:\n");
for (int i = 0; i < totalrows; i++) {
printf("%d %d %d\n", transp[i].row, transp[i].col, transp[i].val);
}
}

int main() {
int totalrows;
int totalcols;
int matrices[50][50];
matrix sparseA[50], transp[50];

printf("Enter the total rows of the matrix: ");
scanf("%d", &totalrows);
printf("Enter the total columns of the matrix: ");
scanf("%d", &totalcols);

for (int i = 0; i < totalrows; i++) {
    for (int j = 0; j < totalcols; j++) {
        printf("Enter the element at (%d, %d) position: ", i + 1, j + 1);
        scanf("%d", &matrices[i][j]);
    }
}

cpynz(totalrows, totalcols, matrices, sparseA);
transpose(totalrows, totalcols, sparseA, transp);
display(totalrows, transp);

return 0;

}