Print the Resulting Matrix
In this step, you will learn how to format and print the resulting matrix in a clean, readable manner.
Enhance the Matrix Printing Function
Open the previous C file:
cd ~/project
nano matrix_addition.c
Update the program with a dedicated matrix printing function:
#include <stdio.h>
#define MAX_SIZE 10
// Function to print matrix
void printMatrix(int matrix[MAX_SIZE][MAX_SIZE], int rows, int cols, const char* matrixName) {
printf("%s:\n", matrixName);
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 matrix1[MAX_SIZE][MAX_SIZE], matrix2[MAX_SIZE][MAX_SIZE], result[MAX_SIZE][MAX_SIZE];
// Previous input code remains the same
// ... (input dimensions and elements of matrix1 and matrix2)
// Add corresponding elements
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Print matrices
printMatrix(matrix1, rows, cols, "First Matrix");
printMatrix(matrix2, rows, cols, "Second Matrix");
printMatrix(result, rows, cols, "Resulting Matrix (Matrix1 + Matrix2)");
return 0;
}
Compile and Run the Program
Compile the updated program:
gcc matrix_addition.c -o matrix_addition
Run the program:
./matrix_addition
Example Output
Enter number of rows (max 10): 2
Enter number of columns (max 10): 3
Enter elements of first matrix:
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 elements of second matrix:
Enter element [0][0]: 7
Enter element [0][1]: 8
Enter element [0][2]: 9
Enter element [1][0]: 10
Enter element [1][1]: 11
Enter element [1][2]: 12
First Matrix:
1 2 3
4 5 6
Second Matrix:
7 8 9
10 11 12
Resulting Matrix (Matrix1 + Matrix2):
8 10 12
14 16 18
Code Explanation
printMatrix()
function is created to print matrices with consistent formatting
%4d
format specifier ensures aligned column printing
- Function takes matrix, dimensions, and a name as parameters
- Matrices are printed with descriptive headers
- Nested loops iterate through matrix elements for printing