Two matrices can be added or subtracted only when they have the same number of rows and columns. Each result element is calculated from the elements at the same row and column in the two input matrices.
#include <stdio.h>
int main(void) {
int first[2][2] = {
{1, 2},
{3, 4}
};
int second[2][2] = {
{5, 6},
{7, 8}
};
int sum[2][2];
for (int row = 0; row < 2; row++) {
for (int column = 0; column < 2; column++) {
sum[row][column] =
first[row][column] + second[row][column];
}
}
for (int row = 0; row < 2; row++) {
for (int column = 0; column < 2; column++) {
printf("%4d", sum[row][column]);
}
putchar('\n');
}
return 0;
}
Output
6 8
10 12
#include <stdio.h>
int main(void) {
int first[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int second[3][3] = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
int sum[3][3];
for (int row = 0; row < 3; row++) {
for (int column = 0; column < 3; column++) {
sum[row][column] =
first[row][column] + second[row][column];
}
}
for (int row = 0; row < 3; row++) {
for (int column = 0; column < 3; column++) {
printf("%d ", sum[row][column]);
}
putchar('\n');
}
return 0;
}
Output
11 22 33
44 55 66
77 88 99
Key change: replace the addition operator with subtraction:
difference[row][column] =
first[row][column] - second[row][column];
#include <stdio.h>
#define MAX 10
int main(void) {
int rows;
int columns;
int first[MAX][MAX];
int second[MAX][MAX];
int sum[MAX][MAX];
printf("Enter rows and columns (1..10): ");
if (scanf("%d %d", &rows, &columns) != 2 ||
rows < 1 || rows > MAX ||
columns < 1 || columns > MAX) {
printf("Invalid matrix size.\n");
return 1;
}
printf("Enter first matrix:\n");
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
if (scanf("%d", &first[row][column]) != 1) {
printf("Invalid input.\n");
return 1;
}
}
}
printf("Enter second matrix:\n");
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
if (scanf("%d", &second[row][column]) != 1) {
printf("Invalid input.\n");
return 1;
}
}
}
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
sum[row][column] =
first[row][column] + second[row][column];
}
}
printf("Sum matrix:\n");
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
printf("%d ", sum[row][column]);
}
putchar('\n');
}
return 0;
}
Addition and subtraction operate element by element. Therefore both input matrices must have the same shape. Matrix multiplication follows a different compatibility rule; see matrix multiplication in C.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.