Sum Of Two Matrix in C-Programming:
We will add two matrix in C-Programming. First we have to know that how to add two matrix. So two matrix can be added if the order of this two matrix are same. Now how the addition is defined? - the matrix addition is defined as in the given picture.Important Tools:
1. array2. for-loop
3. if-else
Code:
#include<stdio.h>
#include<conio.h>
int main()
{
int m,n,m1,n1,a[50][50],i,j,b[50][50],c[50][50];
printf("Enter the order of the first matrix: ");
scanf("%d%d",&m,&n);
printf("Enter the order of the second matrix: ");
scanf("%d%d",&m1,&n1);
//Condition for addition
if(m!=m1||n!=n1)
printf("The sum is not possible");
//The first matrix scan and print
else
{
printf("Enter the first matrix row wise: ");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("The 1st matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
//the second matrix scan and print
printf("Enter the 2nd matrix row wise:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("The 2nd matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n");
}
//addition of two matrix print
printf("The sum of the matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
}
Output:
The output is given belowExplanation:
1. We use <stdio.h> and <conio.h> two header package.2. first of all we check the condition for the addition of two matrix. So we use if-else condition for that. If the order of two matrix is equal then it can be added if not it is impossible.
3. We use m,n,m1,n1,a[50][50],i,j,b[50][50] and c[50][50] variable here. m and n are used for the order of the 1st matrix and n1 and m1 are used for order of 2nd matrix. a[50][50] and b[50][50] are used for store the given two matrices and we used c[50][50] to store and show the sum of two given matrices. And i and j are used in the loop.
4. First we scan and store two matrices in the variable a[50][50] and b[50][50] respectively using for-loop for know more see my post. After that we add the two matrices and store it in the variable c[50][50]. Therefore we print the c[50][50] variable using for-loop.
Better job
ReplyDeleteThank You!!
Delete