Program to add two matrices

Program to add two matrices

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


Program to add two matrices



program-to-add-two-matricesAlgorithm 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

Program to add two matrices

@@coding::1@@


Program to add two matrices using pointers


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


Time complexity: O(n^2)


Recommended Programs









program-to-add-two-matrices

c