Explore
ProGrad Programs
Placement Prep
TCS Codevita
Live Placement Training
Live Aptitude Training
Live Programming Training
Webinars
About Us

Edit
Reply




Edit

Program to add two matrices | FACE Prep

Published on 10 Mar 2020

Program to add two matrices is discussed here. Two matrices are obtained as input from the user. Addition of two matrices is possible only when both the matrices contain same number of rows and columns.

add two matrices

Algorithm to add two matrices


  • Input matrix 1 and matrix 2.
  • If the number of rows and number of columns of matrix 1 and matrix 2 is equal,
  • for i=1 to rows[matrix 1]
  • for j=1 to columns [matrix 1]
  • Input matrix 1 [i,j]
  • Input matrix 2 [i,j]
  • matrix 3 [i,j]= matrix 1 [i,j]+ matrix 2 [i,j];
  • Display matrix 3 [i,j];


Program to add two matrices


C
C++
Java
Python 3

Output
Enter the number of rows and columns : 3 3
Input Matrix 1 elements : 1 0 2 0 3 0 4 0 5
Matrix 1
1 0 2
0 3 0
4 0 5
Input Matrix 2 elements : 1 0 2 0 3 0 4 0 2
Matrix2
1 0 2
0 3 0
4 0 2
Added Matrix
2 0 4
0 6 0
8 0 7


Program to add two matrices using pointers


#include<stdio.h>
#include<stdlib.h>
int i,j;
int** memory(int c,int r){
int **a;
a=(int **)malloc(c*sizeof(int*));
for(i=0;i<c;i++)
*(a+i)=(int *)malloc(r*sizeof(int));
return a;
}
int main()
{
int **a,**b,r,c;
scanf(“%d %d”,&r,&c);
a=memory(c,r);
b=memory(c,r);
for(i=0;i<r;i++){
for(j=0;j<c;j++){
scanf(“%d”,&a[i][j]);
}
}
for(i=0;i<r;i++){
for(j=0;j<c;j++){
scanf(“%d”,&b[i][j]);
}
}for(i=0;i<r;i++){
for(j=0;j<c;j++){
printf(“%d “,a[i][j]+b[i][j]);
}printf(“n”);
}
return 0;
}


Time complexity: O(n^2)


Recommended Programs







If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in