Program to add two matrices using c language.
In
this we took two matrices by name matrix1 and matrix2 which hold the
values of two matrices. And we took another matrix by name res_matrix
to store the result after addition of matrix1 and matrix2. r1,c1
represents the size of first matrix and r2,c2 represents the size of
second matrix.
If the size of two matrices are same ( i.e; r1 , r2 must be same and c1,c2 must be same ) then only we can add two matrices otherwise not possible to add.so first read sizes of two matrix and then check if both the sizes of matrix are equal then read the values of two matrices and find sum.
If the size of two matrices are same ( i.e; r1 , r2 must be same and c1,c2 must be same ) then only we can add two matrices otherwise not possible to add.so first read sizes of two matrix and then check if both the sizes of matrix are equal then read the values of two matrices and find sum.
#include <stdio.h>
void main(){
int matrix1[10][10], matrix2[10][10], res_matrix[10][10], i, j, r1, r2, c1, c2;
// reading the size of first matrix
printf(" enter the size of first matrix <10");
scanf("%d%d", &r1, &c1) ;
// reading the size of second matrix
printf(" enter the size of second matrix <10");
scanf("%d%d", &r2, &c2) ;
//checking the sizes of two matrices for addition
if( r1==r2 && c1==c2){
// reading the elements of first matrix
printf(" enter elements of first matrix ");
for( i=0; i<r1 ;i++){
for(j=0;j<c1;j++){
scanf( "%d", &matrix1[i][j]);
}
}
// reading the elements of second matrix
printf(" enter the elements of second matrix ");
for( i=0; i<r2; i++){
for(j=0; j<c2; j++){
scanf( "%d", &matrix2[i][j]);
}
}
// adding two matrices`
for( i=0; i<r2; i++){
for (j=0; j<c2; j++){
res_matrix[i][j]= matrix1[i][j] + matrix2[i][j];
}
}
// printing the resultant matrix
printf(" the resultant matrix is \n");
for (i=0; i<r1; i++){
for( j=0; j<c1; j++){
printf(" %d ", res_matrix[i][j]);
}
printf(" \n ");
}
}
else printf(" it is not possible to add two matrix as sizes are different ");
}
No comments:
Post a Comment