Module II · Arrays · Two-Dimensional Arrays: Matrix Operations
🎯 Why This Matters
In the last post we saw that a 2-D array is a table of rows and columns. In mathematics, such a table of numbers is called a matrix. Matrices are everywhere: the pixels of a photo, the marks of students across subjects, the prices and quantities in a shop’s records, the rotation of a 3-D game character, and the weights inside machine-learning models.
Two operations are the foundation of everything else you will ever do with matrices: addition and multiplication. They are also the perfect practice for nested loops. Addition needs two loops, multiplication needs three, and understanding why is the key idea of this post.
1️⃣ A Quick Look at a Matrix
A matrix with m rows and n columns is said to have the order m × n. In C we store it in a 2-D array int A[m][n], and the element in row i and column j is A[i][j]. Both indexes start at 0.
Figure 1: A matrix of order 2 x 3 stored in the 2-D array A[2][3].
💡 Remember: the order of a matrix is always written rows × columns. A matrix of order 2 × 3 is not the same as one of order 3 × 2.
2️⃣ Matrix Addition
The Rule
To add two matrices, add the elements that sit in the same position:
C[i][j] = A[i][j] + B[i][j]
Figure 2: The element at position [0][0] of the answer is the sum of the elements at [0][0] of A and B.
For the 2 × 2 example above, there are just four small additions:
Figure 3: Each of the four answer elements comes from one addition.
When Is Addition Possible?
Because each element is paired with the one in the same position, both matrices must have exactly the same order. Otherwise some elements would have no partner.
Figure 4: Addition needs two matrices of the same order. The result also has that order.
The Code Pattern
We visit every position once, so we need a loop for the rows and a loop for the columns inside it. That is why matrix addition uses two nested loops:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
Example 1: Adding Two 2 × 2 Matrices
#include <stdio.h>
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int C[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
printf("A + 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;
}
🖥️ Output:
A + B =
6 8
10 12
The printing loop uses %4d so that every number takes 4 characters, which keeps the columns neatly aligned. The line break \n goes after the inner loop, so that each row of the matrix appears on its own line.
Example 2: Adding Two 3 × 3 Matrices
Here we also display A and B, so that you can check the answer by eye. The matrices were chosen so that every pair adds up to 10.
#include <stdio.h>
int main() {
int A[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int B[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int C[3][3];
// add
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
// display all three
printf("Matrix A:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) printf("%4d", A[i][j]);
printf("\n");
}
printf("\nMatrix B:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) printf("%4d", B[i][j]);
printf("\n");
}
printf("\nA + B:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) printf("%4d", C[i][j]);
printf("\n");
}
return 0;
}
🖥️ Output:
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
9 8 7
6 5 4
3 2 1
A + B:
10 10 10
10 10 10
10 10 10
Example 3: Reading the Matrices from the User
Instead of fixing the numbers inside the program, we can read them. For each row, the user types the numbers separated by spaces.
#include <stdio.h>
int main() {
int A[2][3], B[2][3], C[2][3];
for (int i = 0; i < 2; i++) {
printf("Enter row %d of A (3 numbers): ", i + 1);
for (int j = 0; j < 3; j++) {
scanf("%d", &A[i][j]);
}
}
for (int i = 0; i < 2; i++) {
printf("Enter row %d of B (3 numbers): ", i + 1);
for (int j = 0; j < 3; j++) {
scanf("%d", &B[i][j]);
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
printf("\nSum matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%5d", C[i][j]);
}
printf("\n");
}
return 0;
}
🖥️ Output:
Enter row 1 of A (3 numbers): 1 2 3
Enter row 2 of A (3 numbers): 4 5 6
Enter row 1 of B (3 numbers): 10 20 30
Enter row 2 of B (3 numbers): 40 50 60
Sum matrix:
11 22 33
44 55 66
The same nested-loop structure is used for reading, adding and printing. Only the statement inside the inner loop changes: scanf, then +, then printf.
Example 4: Checking the Order First
A careful program asks for the order of both matrices and only adds them if they match. We keep the arrays large (10 × 10) and use only the part we need.
#include <stdio.h>
int main() {
int A[10][10], B[10][10], C[10][10];
int r1, c1, r2, c2;
printf("Enter rows and columns of A: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and columns of B: ");
scanf("%d %d", &r2, &c2);
if (r1 != r2 || c1 != c2) {
printf("Addition is not possible: the orders are different.\n");
return 0;
}
for (int i = 0; i < r1; i++) {
printf("Enter row %d of A: ", i + 1);
for (int j = 0; j < c1; j++) scanf("%d", &A[i][j]);
}
for (int i = 0; i < r2; i++) {
printf("Enter row %d of B: ", i + 1);
for (int j = 0; j < c2; j++) scanf("%d", &B[i][j]);
}
for (int i = 0; i < r1; i++)
for (int j = 0; j < c1; j++)
C[i][j] = A[i][j] + B[i][j];
printf("\nA + B:\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) printf("%5d", C[i][j]);
printf("\n");
}
return 0;
}
🖥️ Output:
Enter rows and columns of A: 2 2
Enter rows and columns of B: 2 2
Enter row 1 of A: 1 2
Enter row 2 of A: 3 4
Enter row 1 of B: 10 20
Enter row 2 of B: 30 40
A + B:
11 22
33 44
Now try two matrices of different orders (a 2 × 3 and a 3 × 2):
#include <stdio.h>
int main() {
int A[10][10], B[10][10], C[10][10];
int r1, c1, r2, c2;
printf("Enter rows and columns of A: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and columns of B: ");
scanf("%d %d", &r2, &c2);
if (r1 != r2 || c1 != c2) {
printf("Addition is not possible: the orders are different.\n");
return 0;
}
for (int i = 0; i < r1; i++) {
printf("Enter row %d of A: ", i + 1);
for (int j = 0; j < c1; j++) scanf("%d", &A[i][j]);
}
for (int i = 0; i < r2; i++) {
printf("Enter row %d of B: ", i + 1);
for (int j = 0; j < c2; j++) scanf("%d", &B[i][j]);
}
for (int i = 0; i < r1; i++)
for (int j = 0; j < c1; j++)
C[i][j] = A[i][j] + B[i][j];
printf("\nA + B:\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) printf("%5d", C[i][j]);
printf("\n");
}
return 0;
}
🖥️ Output:
Enter rows and columns of A: 2 3
Enter rows and columns of B: 3 2
Addition is not possible: the orders are different.
The condition r1 != r2 || c1 != c2 is true when either the rows or the columns differ. The program politely stops, and never reads any matrix elements.
Example 5: Spotting an Impossible Addition
#include <stdio.h>
int main() {
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int B[3][2] = {{1, 2}, {3, 4}, {5, 6}};
int r1 = 2, c1 = 3, r2 = 3, c2 = 2;
if (r1 != r2 || c1 != c2) {
printf("Addition is not possible: %dx%d and %dx%d have different orders.\n", r1, c1, r2, c2);
} else {
printf("Addition is possible.\n");
}
return 0;
}
🖥️ Output:
Addition is not possible: 2×3 and 3×2 have different orders.
Example 6: A Real-Life Use: Total Marks of Two Tests
Each row is a student and each column is a subject. Adding the two test matrices gives the total marks.
#include <stdio.h>
int main() {
// marks of 3 students in two tests (rows = students, columns = subjects)
int test1[3][2] = {{18, 15}, {12, 20}, {16, 14}};
int test2[3][2] = {{17, 19}, {14, 11}, {20, 18}};
int total[3][2];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
total[i][j] = test1[i][j] + test2[i][j];
}
}
printf("Student Maths Physics\n");
for (int i = 0; i < 3; i++) {
printf(" %d %3d %3d\n", i + 1, total[i][0], total[i][1]);
}
return 0;
}
🖥️ Output:
Student Maths Physics
1 35 34
2 26 31
3 36 32
Example 7: Adding and Summing in One Pass
We can do more than one job inside the same pair of loops. Here we compute C and also keep a running total of all its elements.
#include <stdio.h>
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int C[2][2];
int sum = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
C[i][j] = A[i][j] + B[i][j];
sum = sum + C[i][j];
}
}
printf("Sum of all elements of A + B = %d\n", sum);
return 0;
}
🖥️ Output:
Sum of all elements of A + B = 36
The elements of A + B are 6, 8, 10 and 12, which add up to 36.
3️⃣ Matrix Multiplication
Multiplication is less obvious than addition. You do not simply multiply the elements in matching positions. Instead, every element of the answer is built from a whole row of the first matrix and a whole column of the second.
When Is Multiplication Possible?
The rule is different from addition. The matrices do not need the same order. What matters is that the number of columns of A equals the number of rows of B. The answer then takes its rows from A and its columns from B.
Figure 5: A (m x n) can be multiplied by B (n x p). The result is m x p.
| A | B | Possible? | Order of A × B |
|---|---|---|---|
| 2 × 3 | 3 × 4 | ✅ Yes (3 = 3) | 2 × 4 |
| 2 × 2 | 2 × 2 | ✅ Yes (2 = 2) | 2 × 2 |
| 3 × 1 | 1 × 3 | ✅ Yes (1 = 1) | 3 × 3 |
| 2 × 3 | 2 × 3 | ❌ No (3 ≠ 2) | – |
| 4 × 2 | 3 × 2 | ❌ No (2 ≠ 3) | – |
How One Element Is Calculated
To find C[i][j], take row i of A and column j of B. Multiply the pairs that line up (first with first, second with second, and so on) and add all those products. This is called a row-by-column product (also known as the dot product).
Figure 6: Row 0 of A (orange) meets column 0 of B (purple) to produce C[0][0].
Here, C[0][0] = 1×7 + 2×9 + 3×11 = 7 + 18 + 33 = 58. Repeat this for every position and the whole answer appears:
Figure 7: The complete product, with the calculation of every element.
The Code Pattern: Why Three Loops?
The first two loops visit every position [i][j] of the answer, exactly as in addition. But for each position we must also run along a row of A and down a column of B, adding as we go. That is a third loop, which we call k.
Figure 8: i picks the row, j picks the column, and k does the row-by-column calculation.
for (int i = 0; i < m; i++) { // each row of A
for (int j = 0; j < p; j++) { // each column of B
C[i][j] = 0; // start the total at zero
for (int k = 0; k < n; k++) { // walk along the row and down the column
C[i][j] = C[i][j] + A[i][k] * B[k][j];
}
}
}
Look closely at the indexes in the middle of the formula. A[i][k] keeps the row fixed and moves the column. B[k][j] keeps the column fixed and moves the row. That is exactly “along a row, down a column”.
⚠️ Never forget C[i][j] = 0; before the k loop. We are adding into C[i][j], so it must start at zero for every new element. Without it, the first addition starts from some unknown leftover value and the answer is wrong.
Example 8: Multiplying Two 2 × 2 Matrices
#include <stdio.h>
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int C[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
C[i][j] = 0; // start each answer at 0
for (int k = 0; k < 2; k++) {
C[i][j] = C[i][j] + A[i][k] * B[k][j];
}
}
}
printf("A x 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;
}
🖥️ Output:
A x B =
19 22
43 50
You can verify one element by hand: C[0][0] = 1×5 + 2×7 = 5 + 14 = 19. The other three are 1×6 + 2×8 = 22, 3×5 + 4×7 = 43 and 3×6 + 4×8 = 50.
Example 9: Watching the k Loop Work
To really see what the innermost loop does, here is a program that calculates only C[0][0] and prints every step.
#include <stdio.h>
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int i = 0, j = 0; // we trace only C[0][0]
int sum = 0;
for (int k = 0; k < 2; k++) {
printf("k = %d : A[%d][%d] * B[%d][%d] = %d * %d = %d\n",
k, i, k, k, j, A[i][k], B[k][j], A[i][k] * B[k][j]);
sum = sum + A[i][k] * B[k][j];
printf(" running sum = %d\n", sum);
}
printf("C[0][0] = %d\n", sum);
return 0;
}
🖥️ Output:
k = 0 : A[0][0] * B[0][0] = 1 * 5 = 5
running sum = 5
k = 1 : A[0][1] * B[1][0] = 2 * 7 = 14
running sum = 19
C[0][0] = 19
🔍 Trace:
Start: sum = 0
k = 0 → multiply the 1st number of row 0 (1) by the 1st number of column 0 (5) → 5 → sum = 5
k = 1 → multiply the 2nd number of row 0 (2) by the 2nd number of column 0 (7) → 14 → sum = 19
The loop ends, so C[0][0] = 19.
Example 10: A 2 × 3 Matrix Times a 3 × 2 Matrix
This is the example from the figures. Notice that the k loop runs 3 times, because the matrices share the size 3 (the columns of A and the rows of B).
#include <stdio.h>
int main() {
int A[2][3] = {{1, 2, 3}, {4, 5, 6}}; // 2 x 3
int B[3][2] = {{7, 8}, {9, 10}, {11, 12}}; // 3 x 2
int C[2][2]; // 2 x 2
for (int i = 0; i < 2; i++) { // rows of A
for (int j = 0; j < 2; j++) { // columns of B
C[i][j] = 0;
for (int k = 0; k < 3; k++) { // columns of A = rows of B
C[i][j] += A[i][k] * B[k][j];
}
}
}
printf("A (2x3) x B (3x2) = C (2x2)\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%6d", C[i][j]);
}
printf("\n");
}
return 0;
}
🖥️ Output:
A (2×3) x B (3×2) = C (2×2)
58 64
139 154
Example 11: A 2 × 3 Matrix Times a 3 × 4 Matrix
The matrices do not have to be square. The answer takes the rows of A (2) and the columns of B (4).
#include <stdio.h>
int main() {
int A[2][3] = {{1, 2, 3}, {4, 5, 6}}; // 2 x 3
int B[3][4] = {{1, 0, 2, 1},
{0, 1, 3, 1},
{2, 1, 0, 1}}; // 3 x 4
int C[2][4]; // 2 x 4
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
C[i][j] = 0;
for (int k = 0; k < 3; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
printf("Result (2 x 4):\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 4; j++) {
printf("%5d", C[i][j]);
}
printf("\n");
}
return 0;
}
🖥️ Output:
Result (2 x 4):
7 5 8 6
16 11 23 15
Check the first element: 7 = 1×1 + 2×0 + 3×2. Notice how the loop limits match the orders: i goes up to 2 (rows of A), j up to 4 (columns of B) and k up to 3 (the shared size).
Example 12: Reading Matrices and Checking Compatibility
A complete program asks for both orders, checks the rule c1 == r2, and then multiplies. Here is a valid case: A is 2 × 3 and B is 3 × 2.
#include <stdio.h>
int main() {
int A[10][10], B[10][10], C[10][10];
int r1, c1, r2, c2;
printf("Enter rows and columns of A: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and columns of B: ");
scanf("%d %d", &r2, &c2);
if (c1 != r2) {
printf("Multiplication is not possible: columns of A (%d) != rows of B (%d).\n", c1, r2);
return 0;
}
for (int i = 0; i < r1; i++) {
printf("Enter row %d of A: ", i + 1);
for (int j = 0; j < c1; j++) scanf("%d", &A[i][j]);
}
for (int i = 0; i < r2; i++) {
printf("Enter row %d of B: ", i + 1);
for (int j = 0; j < c2; j++) scanf("%d", &B[i][j]);
}
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
C[i][j] = 0;
for (int k = 0; k < c1; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
printf("\nA x B (%d x %d):\n", r1, c2);
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) printf("%6d", C[i][j]);
printf("\n");
}
return 0;
}
🖥️ Output:
Enter rows and columns of A: 2 3
Enter rows and columns of B: 3 2
Enter row 1 of A: 1 2 3
Enter row 2 of A: 4 5 6
Enter row 1 of B: 7 8
Enter row 2 of B: 9 10
Enter row 3 of B: 11 12
A x B (2 x 2):
58 64
139 154
And here is an invalid case: A is 2 × 3 and B is also 2 × 3.
#include <stdio.h>
int main() {
int A[10][10], B[10][10], C[10][10];
int r1, c1, r2, c2;
printf("Enter rows and columns of A: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and columns of B: ");
scanf("%d %d", &r2, &c2);
if (c1 != r2) {
printf("Multiplication is not possible: columns of A (%d) != rows of B (%d).\n", c1, r2);
return 0;
}
for (int i = 0; i < r1; i++) {
printf("Enter row %d of A: ", i + 1);
for (int j = 0; j < c1; j++) scanf("%d", &A[i][j]);
}
for (int i = 0; i < r2; i++) {
printf("Enter row %d of B: ", i + 1);
for (int j = 0; j < c2; j++) scanf("%d", &B[i][j]);
}
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
C[i][j] = 0;
for (int k = 0; k < c1; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
printf("\nA x B (%d x %d):\n", r1, c2);
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) printf("%6d", C[i][j]);
printf("\n");
}
return 0;
}
🖥️ Output:
Enter rows and columns of A: 2 3
Enter rows and columns of B: 2 3
Multiplication is not possible: columns of A (3) != rows of B (2).
The check c1 != r2 compares the columns of the first with the rows of the second. It is the most important line in the program.
Example 13: Explaining an Impossible Multiplication
#include <stdio.h>
int main() {
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int B[2][3] = {{1, 0, 1}, {0, 1, 0}};
int r1 = 2, c1 = 3, r2 = 2, c2 = 3;
if (c1 != r2) {
printf("Cannot multiply: A is %dx%d and B is %dx%d.\n", r1, c1, r2, c2);
printf("Columns of A (%d) must equal rows of B (%d).\n", c1, r2);
} else {
printf("Multiplication is possible.\n");
}
return 0;
}
🖥️ Output:
Cannot multiply: A is 2×3 and B is 2×3.
Columns of A (3) must equal rows of B (2).
4️⃣ Special Properties Worth Seeing
Property 1: Order Matters (A × B ≠ B × A)
With ordinary numbers, 3 × 4 and 4 × 3 are the same. With matrices, this is usually not true. Swapping the order of multiplication can change the answer, or even make the multiplication impossible.
Figure 9: The same two matrices multiplied in a different order give different results.
Example 14: Showing That A × B ≠ B × A
#include <stdio.h>
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{0, 1}, {1, 0}};
int AB[2][2], BA[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
AB[i][j] = 0;
BA[i][j] = 0;
for (int k = 0; k < 2; k++) {
AB[i][j] += A[i][k] * B[k][j];
BA[i][j] += B[i][k] * A[k][j];
}
}
}
printf("A x B:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) printf("%4d", AB[i][j]);
printf("\n");
}
printf("\nB x A:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) printf("%4d", BA[i][j]);
printf("\n");
}
return 0;
}
🖥️ Output:
A x B:
2 1
4 3
B x A:
3 4
1 2
Matrix B here swaps things around: in A × B it swaps the columns of A, while in B × A it swaps the rows of A.
📝 Note: This is different from addition, where A + B always equals B + A.
Property 2: The Identity Matrix
The identity matrix I is a square matrix with 1s on the main diagonal and 0s everywhere else. Multiplying any matrix by I leaves it unchanged, just like multiplying a number by 1.
Figure 10: Multiplying by the identity matrix returns the original matrix.
Example 15: Multiplying by the Identity
#include <stdio.h>
int main() {
int A[3][3] = {{5, 6, 7}, {8, 9, 1}, {2, 3, 4}};
int I[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
int C[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
C[i][j] = 0;
for (int k = 0; k < 3; k++) {
C[i][j] += A[i][k] * I[k][j];
}
}
}
printf("A x I =\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) printf("%4d", C[i][j]);
printf("\n");
}
return 0;
}
🖥️ Output:
A x I =
5 6 7
8 9 1
2 3 4
Example 16: Squaring a Matrix
Multiplying a square matrix by itself gives its square. This works only for square matrices, because a matrix can only be multiplied by itself if its rows and columns are equal.
#include <stdio.h>
int main() {
int A[2][2] = {{1, 1}, {1, 0}};
int S[2][2]; // S will hold A x A
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
S[i][j] = 0;
for (int k = 0; k < 2; k++) {
S[i][j] += A[i][k] * A[k][j];
}
}
}
printf("A squared =\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) printf("%4d", S[i][j]);
printf("\n");
}
return 0;
}
🖥️ Output:
A squared =
2 1
1 1
The matrix {{1, 1}, {1, 0}} has a famous connection with the Fibonacci numbers. Its powers contain 1, 1, 2, 3, 5, 8, and so on.
5️⃣ Putting It to Work
Example 17: Daily Income of a Shop
This is the kind of problem matrix multiplication was made for. The matrix sold (3 days × 2 items) says how many of each item were sold each day. The matrix price (2 items × 1 column) gives the price of each item. Multiplying them gives the income of each day.
#include <stdio.h>
int main() {
// shop: rows = days, columns = items; prices per item
int sold[3][2] = {{2, 1}, {0, 4}, {3, 3}}; // 3 days x 2 items
int price[2][1] = {{10}, {25}}; // 2 items x 1 column
int income[3][1]; // 3 days x 1 column
for (int i = 0; i < 3; i++) {
income[i][0] = 0;
for (int k = 0; k < 2; k++) {
income[i][0] += sold[i][k] * price[k][0];
}
}
for (int i = 0; i < 3; i++) {
printf("Day %d income = %d\n", i + 1, income[i][0]);
}
return 0;
}
🖥️ Output:
Day 1 income = 45
Day 2 income = 100
Day 3 income = 105
For Day 1: 2×10 + 1×25 = 45. The shared size here is 2, the number of items.
Example 18: Combining Both Operations
We can multiply and add in the same program. Here we calculate (A × B) + D. First the k loop finishes R[i][j], and then we add D[i][j] to it.
#include <stdio.h>
int main() {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int D[2][2] = {{1, 1}, {1, 1}};
int R[2][2];
// R = (A x B) + D
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
R[i][j] = 0;
for (int k = 0; k < 2; k++) {
R[i][j] += A[i][k] * B[k][j];
}
R[i][j] += D[i][j];
}
}
printf("(A x B) + D =\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) printf("%4d", R[i][j]);
printf("\n");
}
return 0;
}
🖥️ Output:
(A x B) + D =
20 23
44 51
We already know that A × B = {{19, 22}, {43, 50}}. Adding a matrix of all 1s gives 20, 23, 44 and 51.
6️⃣ Addition vs Multiplication at a Glance
| Addition | Multiplication | |
|---|---|---|
| Condition | Same order (same rows and same columns) | Columns of A = rows of B |
| Order of result | Same as the inputs | Rows of A × columns of B |
| Formula | C[i][j] = A[i][j] + B[i][j] | C[i][j] = sum of A[i][k] * B[k][j] |
| Loops needed | 2 (i and j) | 3 (i, j and k) |
| Work done | m × n additions | m × n × p multiplications |
| Order matters? | No: A + B = B + A | Yes: A × B is usually not B × A |
| Needs C[i][j] = 0 first? | No (each cell is set directly) | Yes (each cell is built up by adding) |
🚫 Common Mistakes
Mistake 1: Forgetting to Reset C[i][j] to Zero
for (int j = 0; j < p; j++) {
// C[i][j] = 0; ❌ missing!
for (int k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
A local array holds garbage values until you set them. Adding to garbage gives a wrong answer, and the result may change from one run to the next.
Mistake 2: Multiplying Position by Position
C[i][j] = A[i][j] * B[i][j]; // ❌ this is NOT matrix multiplication
That formula multiplies matching elements only. Real matrix multiplication needs the third loop.
Mistake 3: Mixing Up the Loop Limits
For A (m × n) × B (n × p): i runs to m, j runs to p and k runs to n. A common mistake is using the same limit for all three loops, which works only for square matrices.
Mistake 4: Using B[j][k] Instead of B[k][j]
C[i][j] += A[i][k] * B[j][k]; // ❌ walks along a row of B, not down a column
Remember: in A[i][k] * B[k][j] the letter k appears next to each other (the column of A and the row of B). That is the shared size.
Mistake 5: Not Checking the Orders
If the columns of A and the rows of B differ, the program will read elements that do not exist (outside the array), which gives garbage or a crash. Always compare c1 and r2 before multiplying, as in Example 12.
Mistake 6: Putting the Line Break in the Wrong Place
While printing, printf("\n") must come after the inner loop, not inside it. Otherwise every number appears on its own line.
🎓 Practice Exercises
Exercise 1: Predict the Output
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{4, 3}, {2, 1}};
printf("%d %d", A[0][1] + B[0][1], A[1][0] + B[1][0]);
(Answer: 5 5. 2 + 3 = 5 and 3 + 2 = 5.)
Exercise 2: A Row Times a Column
int A[1][3] = {{1, 2, 3}};
int B[3][1] = {{4}, {5}, {6}};
int c = 0;
for (int k = 0; k < 3; k++) c += A[0][k] * B[k][0];
printf("%d", c);
(Answer: 32. 1×4 + 2×5 + 3×6 = 4 + 10 + 18 = 32. A 1 × 3 matrix times a 3 × 1 matrix gives a 1 × 1 matrix, which is a single number.)
Exercise 3: Multiplying by a Scaled Identity
int A[2][2] = {{2, 0}, {0, 2}};
int B[2][2] = {{1, 2}, {3, 4}};
// C = A x B (using the three loops), then print C[0][0] C[0][1] C[1][0] C[1][1]
(Answer: 2 4 6 8. Matrix A is “2 times the identity”, so it doubles every element of B.)
Exercise 4: Orders
A has order 3 × 2 and B has order 2 × 5. Can A × B be calculated? What is the order of the result? Can B × A be calculated?
(Answer: A × B is possible, because the columns of A (2) equal the rows of B (2). The result has order 3 × 5. B × A is not possible, because the columns of B (5) do not equal the rows of A (3).)
Exercise 5: Build It Yourself
- Write a program that reads two 3 × 3 matrices and prints their sum.
- Modify it so that it reads the order of the matrices and refuses to add them if the orders differ.
- Write a program that multiplies a 3 × 3 matrix by a 3 × 3 identity matrix and checks that the result is the same as the original.
- Multiply a 2 × 3 matrix by a 3 × 3 matrix. What is the order of the result?
- Compute
A × BandB × Afor two 2 × 2 matrices of your choice, and compare them. - Extend Example 17 to find the income for a week (7 days) with 3 different items.
❓ Frequently Asked Questions
Q: Why does matrix addition need the same order, while multiplication does not?
Addition pairs element with element, so every element must have a partner. Multiplication pairs a whole row with a whole column, so they only need to be the same length: the columns of A and the rows of B.
Q: Why do we need three loops for multiplication?
Two loops visit every position of the answer. The third loop calculates the value for that position by running along a row and down a column.
Q: What is the order of the result of multiplication?
Rows of the first matrix × columns of the second. For (2 × 3) × (3 × 4) the result is 2 × 4. The shared 3 disappears.
Q: Does A × B always equal B × A?
No, matrix multiplication is not commutative. In Example 14 the two answers were different. In many cases B × A is not even possible.
Q: What is the maximum size of a matrix I can use?
It depends on the array you declare. In our programs, int A[10][10] allows up to 10 × 10. For larger matrices, simply declare a larger array.
Q: Is the order of the loops (i, j, k) important?
For the result, no: you can change the order of the loops and get the same matrix, as long as C[i][j] starts at 0. But the i, j, k order is the clearest one for learning, and it matches how we calculate by hand.
✅ Key Takeaways
- A matrix is a 2-D array. Its order is rows × columns.
- Addition needs two matrices of the same order. It uses
C[i][j] = A[i][j] + B[i][j]inside two nested loops. - Multiplication needs columns of A = rows of B. The result has the rows of A and the columns of B.
- Every element of a product is a row-by-column sum:
C[i][j] = A[i][0]*B[0][j] + A[i][1]*B[1][j] + ... - In code: three nested loops,
C[i][j] = 0;before the innermost loop, thenC[i][j] += A[i][k] * B[k][j];. - Addition is commutative (
A + B = B + A). Multiplication is not (A × Bis usually different fromB × A). - The identity matrix leaves any matrix unchanged when multiplied.
- Always check the orders before you add or multiply, so that your program never reads outside the arrays.
🚀 Keep practising: Work out a 2 × 2 multiplication on paper first, then run your own program and compare. When both agree, you really understand the three loops.
All 29 lessons in this series (open course page)
Part 1 · Getting Started
- Lesson 1: Introduction to C Programming: Overview, Features and Applications
- Lesson 2: The Structure of a C Program: Building Your First Blueprint
- Lesson 3: Identifiers, Keywords and Variables: Naming Things in C Programming
- Lesson 4: Introduction to Algorithms: Thinking Before You Code
- Lesson 5: Introduction to Flowcharts: Drawing the Logic You Already Know
Part 2 · Data Types, Input/Output and Operators
- Lesson 6: Data Types in C: Choosing the Right Box for Every Value
- Lesson 7: Formatted Input and Output in C: Taking Control of printf and scanf
- Lesson 8: Practice Exercise Sheet: Data Types in C
- Lesson 9: Operators and Expressions in C: Assignment, Unary, and Arithmetic
- Lesson 10: Relational, Logical, and Conditional Operators in C
- Lesson 11: Bitwise and Special Operators in C
- Lesson 12: Operator Precedence and Associativity in C
Part 3 · Decisions and Loops
- Lesson 13: Decision and Case Control: if and if-else in C
- Lesson 14: The switch Statement — and switch vs. if-else Ladder
- Lesson 15: The for Loop: Definite Repetition in C
- Lesson 16: while and do-while Loops: Indefinite Repetition in C
- Lesson 17: break and continue in C: Controlling a Loop from the Inside
- Lesson 18: The goto Statement in C: Jumping Around Your Program
Part 4 · Arrays
- Lesson 19: 1-D Arrays in C: Declaration, Address Calculation, Insertion and Deletion
- Lesson 20: Two-Dimensional Arrays in C: Declaration, Initialization and Accessing Elements
- Lesson 21: Matrix Addition and Matrix Multiplication in C
Part 5 · Strings
- Lesson 22: Strings in C: Working with Character Arrays
- Lesson 23: 1-D and 2-D Character Arrays in C: Storing Names and Words
Part 6 · Functions and Scope
- Lesson 24: Functions in C: Declaration and Definition
- Lesson 25: Categories of Functions in C
- Lesson 26: Scope of Variables in C
- Lesson 27: Call by Value in C: How Parameter Passing Works
- Lesson 28: Passing Arrays to Functions in C: Search, Sum and Sort