NBC 103 • Practical #8
2D Matrix Addition & Matrix Multiplication
Aim: To write a C program to perform Matrix Addition and 2D Matrix Multiplication.
Step-by-Step Algorithm & Logic
- 11. Declare matrices A[2][2], B[2][2], and Result[2][2].
- 22. For Matrix Multiplication: Columns of A MUST equal Rows of B.
- 33. Use 3 nested loops: i (0 to r1), j (0 to c2), k (0 to c1).
- 44. Calculate C[i][j] = sum(A[i][k] * B[k][j]).
- 55. Print resulting matrices.
#include <stdio.h>
int main(void) {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int C[2][2] = {0};
// Matrix Multiplication
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
printf("=== Matrix Multiplication (2x2) ===\n");
printf("Matrix A * Matrix B = \n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%4d ", C[i][j]);
}
printf("\n");
}
return 0;
}Sample Input:
A = [[1, 2], [3, 4]], B = [[5, 6], [7, 8]]
Sample Output:
[[19, 22], [43, 50]]
Practical Exam Viva Questions (Exp #8)
1