How to add 2 matrix in c
Algorithm for adding 2 matrices
1) Check the sizes of two matrices math A (m×n) and math B (u X v): if m = u and n = u then display a message matrix addition is possible . Otherwise print matrix not possible Exit .
2) Create a new square matrix of size m×n.
3) For each element in A find the element at the same position at B and add the two values.
Main variables
m1,m2 = 2 matrices 2d arrays
n = Result matrix
i,j = Loop controllers
r,r1,c,c1 = Row and Column
Program
#include<stdio.h>
main()
{
int i,j,r,c,r1,c1,m1[50][50],m2[50][50],n[50][50];
void matsum(int[50][50],int,int);
printf("Enter the number of rows and column of 1st matrix\n");
scanf("%d %d",&r,&c);
printf("Enter the elements of matrix 1");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&m1[i][j]);
}
}
printf("Enter the number of rows and column of 2nd matrix\n");
scanf("%d %d",&r1,&c1);
printf("Enter the elements of matrix 2");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&m2[i][j]);
}
}
if((r1==r)&&(c1==c))
{
for(i=0;i<r;i++)
for(j=0;j<c1;j++)
{
n[i][j]=0;
n[i][j]=m1[i][j]+m2[i][j];
}
matsum(n,r,c1);
}
else
printf("Matrix addition not possible\n");
}
void matsum(int x[50][50],int y,int z)
{
int i,j;
printf("Sum of the matrices is \n");
for(i=0;i<y;i++)
{
for(j=0;j<z;j++)
{
printf("%d",x[i][j]);
printf("\t");
}
printf("\n");
}}
Output
Enter the number of rows and column of 1st matrix
2 2
Enter the elements of matrix
1 1
1 1
Enter the number of rows and column of 2nd matrix
2 2
Enter the elements of matrix
2 2
2 2
Sum of the matrices is
3 3
3 3
No comments:
Post a Comment