2. matrix #include struct term { int row; int col; int value; }; void readSparse(struct term a[]) { int i, rows, cols, n; printf("Enter total rows and columns of matrix: "); scanf("%d%d", &rows, &cols); printf("Enter total non-zero elements: "); scanf("%d", &n); a[0].row = rows; a[0].col = cols; a[0].value = n; for(i = 1; i <= n; i++) { printf("Enter row, column and value for element %d: ", i); scanf("%d%d%d", &a[i].row, &a[i].col, &a[i].value); } } void displaySparse(struct term a[]) { int i, n = a[0].value; printf("\nRow\tCol\tValue\n"); for(i = 0; i <= n; i++) { printf("%d\t%d\t%d\n", a[i].row, a[i].col, a[i].value); } } void simpleTranspose(struct term a[], struct term b[]) { int i, j, n = a[0].value; b[0].row = a[0].col; b[0].col = a[0].row; b[0].value = n; int currentb = 1; for(i = 0; i < a[0].col; i++) { for(j = 1; j <= n; j++) { if(a[j].col == i) { b[currentb].row = a[j].col; b[currentb].col = a[j].row; b[currentb].value = a[j].value; currentb++; } } } } void fastTranspose(struct term a[], struct term b[]) { int rowTerms[20], startingPos[20]; int i, j, numCols = a[0].col, numTerms = a[0].value; b[0].row = numCols; b[0].col = a[0].row; b[0].value = numTerms; if(numTerms > 0) { for(i = 0; i < numCols; i++) rowTerms[i] = 0; for(i = 1; i <= numTerms; i++) rowTerms[a[i].col]++; startingPos[0] = 1; for(i = 1; i < numCols; i++) startingPos[i] = startingPos[i-1] + rowTerms[i-1]; for(i = 1; i <= numTerms; i++) { j = startingPos[a[i].col]++; b[j].row = a[i].col; b[j].col = a[i].row; b[j].value = a[i].value; } } } int main() { struct term a[20], b[20]; int choice; readSparse(a); printf("\nOriginal Sparse Matrix:"); displaySparse(a); printf("\nChoose Operation:\n"); printf("1. Simple Transpose\n"); printf("2. Fast Transpose\n"); printf("Enter your choice: "); scanf("%d", &choice); switch(choice) { case 1: simpleTranspose(a, b); printf("\nAfter Simple Transpose:"); displaySparse(b); break; case 2: fastTranspose(a, b); printf("\nAfter Fast Transpose:"); displaySparse(b); break; default: printf("Invalid choice!\n"); } return 0; }