Matrix Multiplication
#include <stdio.h>
int main() {
int r1, c1, r2, c2, i, j, k;
// Input dimensions
printf("Enter rows and columns of first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and columns of second matrix: ");
scanf("%d %d", &r2, &c2);
// Check condition
if(c1 != r2) {
printf("Matrix multiplication not possible.\n");
return 0;
}
int A[r1][c1], B[r2][c2], C[r1][c2];
// Input first matrix
printf("Enter elements of first matrix:\n");
for(i = 0; i < r1; i++) {
for(j = 0; j < c1; j++) {
scanf("%d", &A[i][j]);
}
}
// Input second matrix
printf("Enter elements of second matrix:\n");
for(i = 0; i < r2; i++) {
for(j = 0; j < c2; j++) {
scanf("%d", &B[i][j]);
}
}
// Initialize result matrix to 0
for(i = 0; i < r1; i++) {
for(j = 0; j < c2; j++) {
C[i][j] = 0;
}
}
// Matrix multiplication
for(i = 0; i < r1; i++) {
for(j = 0; j < c2; j++) {
for(k = 0; k < c1; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Display result
printf("Resultant Matrix:\n");
for(i = 0; i < r1; i++) {
for(j = 0; j < c2; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
return 0;
}
Explanation
A[r1][c1] → First matrix
B[r2][c2] → Second matrix
C[r1][c2] → Result matrix
Core Logic:
C[i][j] += A[i][k] * B[k][j];
Multiplyrow of A with column of B
Sum all products
Example
Matrix A:
12
34
Matrix B:
56
78
Result
19 22
43 50
Transpose Of a Matrix
Transpose of a matrix means rows become columns:
A [i] [j] \rightarrow A [j] [i]
C Program
#include <stdio.h>
int main() {
int r, c, i, j;
printf("Enter rows and columns of matrix: ");
scanf("%d %d", &r, &c);
int A[r][c], T[c][r];
// Input matrix
printf("Enter elements of matrix:\n");
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
scanf("%d", &A[i][j]);
}
}
// Find transpose
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
T[j][i] = A[i][j];
}
}
// Display original matrix
printf("Original Matrix:\n");
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
printf("%d ", A[i][j]);
}
printf("\n");
}
// Display transpose matrix
printf("Transpose Matrix:\n");
for(i = 0; i < c; i++) {
for(j = 0; j < r; j++) {
printf("%d ", T[i][j]);
}
printf("\n");
}
return 0;
}
Explanation
Original
matrix: A[r][c]
Transpose matrix: T[c][r]
Logic:
T[j][i] = A[i][j];
→ swap row and column indices
Example
Original Matrix:
123
456
Transpose
14
25
36