Matrix addition in C language to add two matrices, i.e., compute their sum and print it. A user inputs their orders (number of rows and columns) and the matrices. For example, if the order is 2, 2, i.e., two rows and two columns and the matrices are:
First matrix:
1 2
3 4
Second matrix:
4 5
-1 5
The output is:
5 7
2 9
Addition of two matrix in C
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}
Output of the program:
Download Add Matrix program.
In the above program we have used three nested for loops (one loop inside another loop). There's an another way to write the program. We initialise the matrix which stores the sum of the matrices with the first matrix elements and add the second matrix elements while the user inputs them. Let's implement it through a program.
C program for matrix addition
int main()
{
int m, n, p, q, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns in the matrices\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of the first matrix\n");
for (p = 0; p < m; p++)
for (q = 0; q < n; q++) {
scanf("%d", &first[p][q]);
sum[p][q] = first[p][q];
}
printf("Enter the elements of the second matrix\n");
for (p = 0; p < m; p++)
for (q = 0 ; q < n; q++) {
scanf("%d", &second[p][q]);
sum[p][q] = sum[p][q] + second[p][q];
}
printf("Sum of the matrices:\n");
for (p = 0; p < m; p++) {
for (q = 0 ; q < n; q++) {
printf("%d\t", sum[p][q]);
}
printf("\n");
}
return 0;
}
Similarly, we can create a program to subtract two matrices. You can also create a function to perform the addition.
Matrices are used in programming to represent graph data structure, in solving linear equations, and in many other ways.