AdvancedC Programming · Lesson 21 of 21 · Updated ·
Matrix Programs in C — Addition, Transpose, Multiplication, Symmetric Check and Spiral Print
A matrix is a table of numbers with rows and columns. In C it is stored in a 2D array: int a[3][4] has 3 rows and 4 columns, and a[i][j] is the value in row i, column j (both counting from 0). The arrays lesson showed how to declare and print one, and the pointers and 2D arrays lesson showed how it sits in memory. This lesson writes the matrix programs that C practical exams and coding rounds ask for again and again.
Every program here is built from one pattern: two nested loops, the outer one over rows i, the inner one over columns j.
1. Addition and transpose
Addition adds the values in the same position: c[i][j] = a[i][j] + b[i][j]. Both matrices must have the same size.
The transpose turns rows into columns: t[j][i] = a[i][j]. A matrix with 2 rows and 3 columns (a 2 × 3 matrix) has a 3 × 2 transpose.
#include <stdio.h>
int main(void) {
int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
int b[2][3] = {{10, 20, 30}, {40, 50, 60}};
int sum[2][3], t[3][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++) {
sum[i][j] = a[i][j] + b[i][j];
t[j][i] = a[i][j]; /* row i becomes column i */
}
printf("a + b:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) printf("%4d", sum[i][j]);
printf("\n");
}
printf("transpose of a:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) printf("%4d", t[i][j]);
printf("\n");
}
return 0;
}
a + b:
11 22 33
44 55 66
transpose of a:
1 4
2 5
3 6
%4d prints each number in a column 4 characters wide, so the output lines up like a real table.
2. Row and column totals: a marks table
A common practical question: store the marks of 3 students in 4 subjects, then print each student's total and each subject's average. A row total adds across one row (fix i, loop over j); a column total adds down one column (fix j, loop over i).
#include <stdio.h>
int main(void) {
int marks[3][4] = {
{78, 85, 62, 90}, /* student 0 */
{55, 70, 88, 64}, /* student 1 */
{91, 66, 74, 81} /* student 2 */
};
for (int i = 0; i < 3; i++) {
int total = 0;
for (int j = 0; j < 4; j++) total += marks[i][j];
printf("student %d total: %d\n", i, total);
}
for (int j = 0; j < 4; j++) {
int total = 0;
for (int i = 0; i < 3; i++) total += marks[i][j];
printf("subject %d average: %.2f\n", j, total / 3.0);
}
return 0;
}
student 0 total: 315
student 1 total: 277
student 2 total: 312
subject 0 average: 74.67
subject 1 average: 73.67
subject 2 average: 74.67
subject 3 average: 78.33
Dividing by 3.0 instead of 3 makes the division happen in floating point, so the average keeps its decimals.
3. Matrix multiplication
Multiplication is not done position by position. The value in row i, column j of the product is the row i of A multiplied element by element with column j of B, then added up:
c[i][j] = a[i][0]*b[0][j] + a[i][1]*b[1][j] + … + a[i][n-1]*b[n-1][j]
For this to work, a row of A must be as long as a column of B. Rule: an m × n matrix can be multiplied by an n × p matrix, and the result is m × p. The two inner sizes (n) must match.
#include <stdio.h>
int main(void) {
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] = {0}; /* 2 x 2 result, start at 0 */
for (int i = 0; i < 2; i++) /* each row of a */
for (int j = 0; j < 2; j++) /* each column of b */
for (int k = 0; k < 3; k++) /* walk along the row and column */
c[i][j] += a[i][k] * b[k][j];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) printf("%5d", c[i][j]);
printf("\n");
}
return 0;
}
58 64
139 154
Check one value by hand: c[0][0] = 1×7 + 2×9 + 3×11 = 7 + 18 + 33 = 58.
Three nested loops means multiplying two n × n matrices takes about n³ multiplications: for n = 100, a million. Also note that A × B is usually not equal to B × A — here B × A would even be a 3 × 3 matrix.
4. Diagonals and the symmetric check
These ideas only apply to square matrices (same number of rows and columns, n × n).
- The main diagonal holds the elements where
i == j. Their sum is called the trace. - The secondary diagonal goes from top-right to bottom-left: elements where
i + j == n - 1. - A matrix is symmetric if it equals its transpose:
a[i][j] == a[j][i]for everyiandj.
#include <stdio.h>
#define N 3
int is_symmetric(int a[N][N]) {
for (int i = 0; i < N; i++)
for (int j = i + 1; j < N; j++) /* only above the diagonal */
if (a[i][j] != a[j][i]) return 0;
return 1;
}
int main(void) {
int s[N][N] = {{2, 7, 3}, {7, 4, 5}, {3, 5, 6}};
int m[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int main_d = 0, second_d = 0;
for (int i = 0; i < N; i++) {
main_d += m[i][i];
second_d += m[i][N - 1 - i];
}
printf("main diagonal: %d, secondary: %d\n", main_d, second_d);
printf("s symmetric: %d, m symmetric: %d\n", is_symmetric(s), is_symmetric(m));
return 0;
}
main diagonal: 15, secondary: 15
s symmetric: 1, m symmetric: 0
The symmetric check starts j at i + 1. Checking only the part above the diagonal is enough, because each pair (i, j) and (j, i) is compared once, and the diagonal always equals itself.
5. Spiral order
A favourite coding-round question: print the matrix in a spiral — across the top row, down the right column, back along the bottom row, up the left column, then repeat on the inside.
Keep four boundaries: top, bottom, left, right. After printing a side, move that boundary inwards. Stop when the boundaries cross.
#include <stdio.h>
#define R 3
#define C 4
int main(void) {
int a[R][C] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
int top = 0, bottom = R - 1, left = 0, right = C - 1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; j++) printf("%d ", a[top][j]);
top++;
for (int i = top; i <= bottom; i++) printf("%d ", a[i][right]);
right--;
if (top <= bottom) { /* a bottom row is still left */
for (int j = right; j >= left; j--) printf("%d ", a[bottom][j]);
bottom--;
}
if (left <= right) { /* a left column is still left */
for (int i = bottom; i >= top; i--) printf("%d ", a[i][left]);
left++;
}
}
printf("\n");
return 0;
}
1 2 3 4 8 12 11 10 9 5 6 7
The two if checks matter. Without them, a matrix with a single remaining row or column would print some values twice. Test spiral code with a non-square matrix like this 3 × 4 one; a square matrix can hide the bug.
Common mistakes
- Multiplying matrices position by position (
c[i][j] = a[i][j] * b[i][j]). That is not matrix multiplication. - Forgetting to start the product matrix at 0 before adding into it with
+=. - Multiplying without checking the size rule: columns of A must equal rows of B.
- Swapping
iandjlimits for a non-square matrix, reading outside the array. - Transposing a square matrix in place with
jstarting at 0: every pair is swapped twice, giving back the original. Startjati + 1. - Missing the boundary checks in spiral code, so values repeat.
Quick recap
- Two nested loops: outer over rows
i, inner over columnsj. - Addition: same position, same size. Transpose:
t[j][i] = a[i][j]. - Row total fixes
i; column total fixesj. - Multiplication:
c[i][j] += a[i][k] * b[k][j]; m × n times n × p gives m × p; O(n³). - Main diagonal
i == j, secondaryi + j == n - 1; symmetric meansa[i][j] == a[j][i]. - Spiral: four boundaries, shrink after each side, check before the bottom row and left column.