Matrix Addition Program
Get ready to explore the fascinating world of C programming once more! In this blog post, we're delving into the realm of matrices and operations as we learn how to write a C program for matrix addition. We'll guide you through every step, helping you grasp the essentials of coding while creating a practical program that performs matrix addition for two 2x2 matrices. Whether you're new to programming or looking to expand your skills, this guide is your key to understanding matrix manipulation. So let's jump in and uncover the magic of C programming as we unlock the secrets of matrix addition together!
Discover how to write a C program that performs matrix addition for two 2x2 matrices using this informative guide.
#include <stdio.h>
int main() {
int matrix1[2][2], matrix2[2][2], sum[2][2];
printf("Enter elements of first matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
scanf("%d", &matrix1[i][j]);
}
}
printf("Enter elements of second matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
scanf("%d", &matrix2[i][j]);
}
}
printf("Sum of matrices:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
Test the Program
Enter elements of first matrix (4 values, separated by spaces):
Enter elements of second matrix (4 values, separated by spaces):
Explanation
-
Step 1:
The program starts by including the standard input/output library
stdio.h
. -
Step 2:
In the
main()
function, integer arraysmatrix1
,matrix2
, andsum
are declared to store the matrices and their sum. -
Step 3:
A nested
for
loop is used to input elements of both matrices. -
Step 4:
Another nested
for
loop is used to calculate the sum of corresponding elements and store it in thesum
array. -
Step 5:
The program displays the sum matrix using
printf()
.
If you have any doubts, Please let me know