Write a program to multiply two matrices.
Learn how to multiply two matrices in C programming
๐งพ Step-by-Step Explanation
๐น Step 1: Include Header File
#include <stdio.h>
This standard library provides essential functions:
printf()
for displaying outputscanf()
for reading user input- Basic console I/O operations
๐น Step 2: Declare Matrices and Variables
int A[10][10], B[10][10], C[10][10];
int r1, c1, r2, c2, i, j, k;
- A, B, C: 10×10 matrices (2D arrays)
- r1, c1: Rows and columns of Matrix A
- r2, c2: Rows and columns of Matrix B
- i, j, k: Loop counters for matrix operations
๐น Step 3: Input Matrix Dimensions
printf("Enter rows and columns for matrix A: ");
scanf("%d%d", &r1, &c1);
printf("Enter rows and columns for matrix B: ");
scanf("%d%d", &r2, &c2);
- Gets dimensions for both matrices from user
- Uses
%d%d
to read two integers at once - Maximum size is 10×10 as declared
๐น Step 4: Check Multiplication Condition
if(c1 != r2) {
printf("Matrix multiplication not possible.\n");
return 0;
}
- Verifies columns of A match rows of B
- Matrix multiplication requires this condition
- Exits program if condition fails
๐น Step 5: Input Matrix Elements
for(i = 0; i < r1; i++) {
for(j = 0; j < c1; j++) {
scanf("%d", &A[i][j]);
}
}
- Nested loops to read each matrix element
- First for rows, second for columns
- Same process for both matrices A and B
- Displays position with each input prompt
๐น Step 6: Multiply Matrices
for(i = 0; i < r1; i++) {
for(j = 0; j < c2; j++) {
C[i][j] = 0;
for(k = 0; k < c1; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
Matrix multiplication algorithm:
- Outer loops: Iterate through result matrix positions
- Inner loop: Computes dot product of row from A and column from B
- Initialization: Sets result position to 0 before accumulation
- Accumulation: Sums products of corresponding elements
๐น Step 7: Display Result Matrix
for(i = 0; i < r1; i++) {
for(j = 0; j < c2; j++) {
printf("%d\t", C[i][j]);
}
printf("\n");
}
- Prints result matrix in tabular format
- Uses
\t
for column alignment - Uses
\n
after each row - Shows final product of matrix multiplication
๐งช Sample Output
Enter rows and columns for matrix A: 2 3
Enter rows and columns for matrix B: 3 2
Enter elements of matrix A:
A[0][0]: 1
A[0][1]: 2
A[0][2]: 3
A[1][0]: 4
A[1][1]: 5
A[1][2]: 6
Enter elements of matrix B:
B[0][0]: 7
B[0][1]: 8
B[1][0]: 9
B[1][1]: 10
B[2][0]: 11
B[2][1]: 12
Resultant Matrix C (A x B):
58 64
139 154