Q-18: Write a C/C++ program to find the sum of two matrices.
    

Using - C


#include<stdio.h> void main() { int rows, cols, i,j; printf("Enter number of rows: "); scanf("%d",&rows); printf("Enter number of columns: "); scanf("%d",&cols); int a[rows][cols], b[rows][cols], c[rows][cols]; printf("Enter Elements of 1st Matrix: \n"); for(i=0; i < rows; i++) { for(j=0; j < cols; j++) { scanf("%d",&a[i][j]); } } printf("Enter Elements of 2nd Matrix: \n"); for(i=0; i < rows; i++) { for(j=0; j < cols; j++) { scanf("%d",&b[i][j]); } } for(i=0; i < rows; i++) { for(j=0; j < cols; j++) { c[i][j] = a[i][j] + b[i][j]; } } printf("\n\nSUM OF TWO MATRICES:\n"); for(i=0; i < rows; i++) { for(j=0; j < cols; j++) { printf("%d ",c[i][j]); } printf("\n"); } }

OUTPUT

Enter number of rows:  2
Enter number of columns:  2
Enter Elements of 1st Matrix:
10   12
21   24
Enter Elements of 2nd Matrix:
12   15
32   20
  
  
SUM OF TWO MATRICES:
22   27
53   44
        

Using - C++


#include<iostream> using namespace std; int main() { int rows, cols, i,j; cout<< "Enter number of rows: "; cin>> rows; cout<< "Enter number of columns: "; cin>> cols; int a[rows][cols], b[rows][cols], c[rows][cols]; cout<< "Enter Elements of 1st Matrix: \n"; for(i=0; i < rows; i++) { for(j=0; j < cols; j++) { cin>> a[i][j]; } } cout<< "Enter Elements of 2nd Matrix: \n"; for(i=0; i < rows; i++) { for(j=0; j < cols; j++) { cin>> b[i][j]; } } for(i=0; i < rows; i++) { for(j=0; j < cols; j++) { c[i][j] = a[i][j] + b[i][j]; } } cout<< "\n\nSUM OF TWO MATRICES:\n"; for(i=0; i < rows; i++){ for(j=0; j < cols; j++){ cout<< c[i][j]<< " "; } cout<< "\n"; } }

OUTPUT

Enter number of rows:  3
Enter number of columns:  3
Enter Elements of 1st Matrix:
10   20   30
15   35   25
36   21   28
Enter Elements of 2nd Matrix:
12   14   16
19   17   21
32   33   55
  
  
SUM OF TWO MATRICES:
22   34   46
34   52   46
68   54   83