In: Computer Science
Write a program that reads two square Matrices of size 2 *2 and calculate and print the sum of them. Also, the signed value of the matrices are input by the user Note: 1) Use CamelCase for variables names 2) Write Comments such as your name, the class, description of the program, and description of your logic. 4) Use sematic names for your variables 5) Your program should be C program not C++.
The source code and output are as follows:
#include <stdio.h>
int main() {
int a[2][2], b[2][2], sumMatrix[2][2], i, j;// camelCase used
int r=2,c=2; // square matrix of size 2*2
printf("\nEnter elements of 1st matrix:\n");// Reading matrix a
for (i = 0; i < r; ++i)
for (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"); // Reading matrix b
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", &b[i][j]);
}
// adding two matrices
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
sumMatrix[i][j] = a[i][j] + b[i][j];
}
// printing the result
printf("\nSum of two matrices: \n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("%d ", sumMatrix[i][j]);
if (j == c - 1) {
printf("\n\n");
}
}
return 0;
}
Output: