Print the Transposed Matrix
In this final step, you'll learn how to format and print the transposed matrix with improved readability and error handling. We'll enhance the previous program to make the output more professional.
Open the matrix_transpose.c file:
cd ~/project
nano matrix_transpose.c
Replace the previous code with the following improved implementation:
#include <stdio.h>
#define MAX_ROWS 100
#define MAX_COLS 100
void printMatrix(int matrix[MAX_ROWS][MAX_COLS], int rows, int cols, const char* title) {
printf("%s:\n", title);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%4d ", matrix[i][j]);
}
printf("\n");
}
printf("\n");
}
int main() {
int rows, cols;
int matrix[MAX_ROWS][MAX_COLS];
int transposed[MAX_COLS][MAX_ROWS];
// Input validation
do {
printf("Enter number of rows (1-%d): ", MAX_ROWS);
scanf("%d", &rows);
} while (rows <= 0 || rows > MAX_ROWS);
do {
printf("Enter number of columns (1-%d): ", MAX_COLS);
scanf("%d", &cols);
} while (cols <= 0 || cols > MAX_COLS);
// Input matrix elements
printf("Enter matrix elements:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// Transpose the matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transposed[j][i] = matrix[i][j];
}
}
// Print matrices with formatted output
printMatrix(matrix, rows, cols, "Original Matrix");
printMatrix(transposed, cols, rows, "Transposed Matrix");
return 0;
}
Compile and run the program:
gcc matrix_transpose.c -o matrix_transpose
./matrix_transpose
Example output:
Enter number of rows (1-100): 3
Enter number of columns (1-100): 3
Enter matrix elements:
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter element [2][0]: 7
Enter element [2][1]: 8
Enter element [2][2]: 9
Original Matrix:
1 2 3
4 5 6
7 8 9
Transposed Matrix:
1 4 7
2 5 8
3 6 9
Key improvements in this version:
- Added input validation for matrix dimensions
- Created a separate
printMatrix()
function for better code organization
- Improved matrix printing with aligned formatting using
%4d
- Added titles to matrix output for clarity
- Handles different matrix sizes more robustly