Write a C program to add two matrices
Description: Take the elements of two 2 x 2 matrices as input. Print the sum matrix.
Hint:
- Add the elements which are at the same row and column:
sum[i][j] = a[i][j] + b[i][j].
C program to add two matrices
#include <stdio.h>
int main(void) {
int a[2][2], b[2][2], sum[2][2];
printf("Enter 4 elements of the first matrix: ");
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
scanf("%d", &a[i][j]);
printf("Enter 4 elements of the second matrix: ");
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
scanf("%d", &b[i][j]);
printf("Sum of the matrices:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum[i][j] = a[i][j] + b[i][j];
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
Output:
Output of the above program is
Enter 4 elements of the first matrix: 1
2
3
4
Enter 4 elements of the second matrix: 5
6
7
8
Sum of the matrices:
6 8
10 12
How it works
- The nested loops go through each row and each column.
- The result matrix has two rows: 6 8 and 10 12.
Read C Two Dimensional Arrays.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |