Matrix Addition program in C
Two matrices can be added element by element in C. This is achieved using nested for loops, where the outer loop signifies the row and inner loop signifies the column.
C program to find addition of two matrices
#include <stdio.h>
int main() {
int r, c;
printf("Enter the number of rows(r): ");
scanf("%d", & r);
printf("Enter the number of columns(c): ");
scanf("%d", & c);
int a[r][c], b[r][c];
printf("\nEnter elements of 1st matrix:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a[%d][%d]: ", i + 1, j + 1);
scanf("%d", & a[i][j]);
}
printf("Enter elements of 2nd matrix:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element b[%d][%d]: ", i + 1, j + 1);
scanf("%d", & b[i][j]);
}
int sum[r][c];
//now add elements of two matrices
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
sum[i][j] = a[i][j] + b[i][j];
}
//output the result
printf("\nSum of two matrices: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", sum[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}
Output
Output of this program will be −
Enter the number of rows(r): 3 Enter the number of columns(c): 3 Enter elements of 1st matrix: Enter element a[1][1]: 1 Enter element a[1][2]: 2 Enter element a[1][3]: 3 Enter element a[2][1]: 4 Enter element a[2][2]: 5 Enter element a[2][3]: 6 Enter element a[3][1]: 7 Enter element a[3][2]: 8 Enter element a[3][3]: 9 Enter elements of 2nd matrix: Enter element b[1][1]: 9 Enter element b[1][2]: 8 Enter element b[1][3]: 7 Enter element b[2][1]: 6 Enter element b[2][2]: 5 Enter element b[2][3]: 4 Enter element b[3][1]: 3 Enter element b[3][2]: 2 Enter element b[3][3]: 1 Sum of two matrices: 10 10 10 10 10 10 10 10 10
Advertisements