#include <stdio.h>
void main() {
float a[2][2], b[2][2], c[2][2]; // Declare three 2x2 matrices
int i, j;
printf("Enter the elements of the 1st matrix:\n");
// Reading the first matrix
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++) {
scanf("%f", &a[i][j]);
}
printf("Enter the elements of the 2nd matrix:\n");
// Reading the second matrix
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++) {
scanf("%f", &b[i][j]);
}
// Calculating the sum of the two matrices
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++) {
c[i][j] = a[i][j] + b[i][j]; // Sum of corresponding elements
}
// Displaying the resulting sum matrix
printf("\nSum of the matrices:\n");
for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++) {
printf("%f ", c[i][j]); // Print each element
}
printf("\n"); // New line after each row
}
}
Explanation of the Code
Header File Inclusion
#include <stdio.h>
This line includes the standard input-output library, which is necessary for using functions like
printf
andscanf
.Main Function
void main() {
The
main
function is where the program execution starts. It is defined with a return type ofvoid
here, but it’s generally recommended to useint main()
in C for standard compliance.Matrix Declaration
float a[2][2], b[2][2], c[2][2];
Three 2×2 matrices are declared:
a
for the first matrix,b
for the second, andc
for the resulting sum matrix.Input for First Matrix
printf("Enter the elements of the 1st matrix:\n"); for(i = 0; i < 2; i++) for(j = 0; j < 2; j++) { scanf("%f", &a[i][j]); }
The user is prompted to enter the elements of the first matrix. A nested loop is used to read each element
Input for Second Matrix
printf("Enter the elements of the 2nd matrix:\n"); for(i = 0; i < 2; i++) for(j = 0; j < 2; j++) { scanf("%f", &b[i][j]); }
Similarly, the user is prompted to enter the elements of the second matrix, again using a nested loop.
Matrix Addition
for(i = 0; i < 2; i++) for(j = 0; j < 2; j++) { c[i][j] = a[i][j] + b[i][j]; // Sum of corresponding elements }
This nested loop iterates through each element of the matrices
a
andb
, adding the corresponding elements together and storing the result in the matrixc
.Display Resulting Matrix
printf("\nSum of the matrices:\n"); for(i = 0; i < 2; i++) { for(j = 0; j < 2; j++) { printf("%f ", c[i][j]); // Print each element } printf("\n"); // New line after each row }
This section prints the resulting sum matrix
c
. Each element is printed in a formatted manner, with a new line after each row for clarity.
Output
When you run the program, it will prompt you to enter the elements of the two matrices and then display their sum.
Example Input:
Enter the elements of the 1st matrix:
1 2
3 4
Enter the elements of the 2nd matrix:
5 6
7 8
Example Output:
Sum of the matrices:
6.000000 8.000000
10.000000 12.000000