C Program to Add Two Matrices

In this source code example, we will write a C program to add two matrices using a two-dimensional array.

C Program to Add Two Matrices

#include<stdio.h>
void main() {
	int i, j, m, n, p, q;
	int a[10][10], b[10][10], c[10][10];
	printf("\nEnter no of rows and column of matrixA:");
	scanf("%d%d", &m, &n);
	printf("\nEnter no of rows and column of matrixB:");
	scanf("%d%d", &p, &q);
	if (m != p && n != q) {
		printf("\n Matrix cannot be added.");
	}
	printf("\n Matrix can be added");

	printf("\n Enter elements of matrix A:");
	for (i = 0; i < m; i++)
		for (j = 0; j < n; j++)
			scanf("%d", &a[i][j]);

	printf("\n Enter elements of matrix B:");
	for (i = 0; i < p; i++)
		for (j = 0; j < q; j++)
			scanf("%d", &b[i][j]);
	for (i = 0; i < m; i++)
		for (j = 0; j < n; j++)
			c[i][j] = a[i][j] + b[i][j];

	printf("\n Display matrix A:\n");
	for (i = 0; i < m; i++) {
		for (j = 0; j < n; j++)
			printf("%d\t", a[i][j]);
		printf("\n");
	}

	printf("\n Display matrix B:\n");
	for (i = 0; i < p; i++) {
		for (j = 0; j < q; j++)
			printf("%d\t", b[i][j]);
		printf("\n");
	}

	printf("\n Display matrix C:\n");
	for (i = 0; i < p; i++) {
		for (j = 0; j < q; j++)
			printf("%d\t", c[i][j]);
		printf("\n");
	}
}

Output:


Enter no of rows and column of matrixA:2
2

Enter no of rows and column of matrixB:2
2

 Matrix can be added
 Enter elements of matrix A:1
2
3
4

 Enter elements of matrix B:4
3
2
1

 Display matrix A:
1	2	
3	4	

 Display matrix B:
4	3	
2	1	

 Display matrix C:
5	5	
5	5	

Comments