Addition of two matrix in C++

How It Works:

    • For 2D array size there must be constant value in square brackets like 
      array[constant value][constant value].

       

  • Two const variables row and col are used to define size.
  • if we do not make both const then error found because without const reserve word they are behaving as variable.
  • Before placing both variable in square brackets they must initialized else error will be found.
  • 3 nested for loops are used two for taking input in matrix 2D arrays and one for resultant matrix.

Here is the program for addition of two matrix in C++

CODE:

#include<iostream>
using namespace std;

int main(){

//Using const int for array size
    const int row=2,col=2;
// if not use const error found

cout<<"Size of Matrices : "<<row<<" X "<<col<<endl;
cout<<"Enter Value For First Matrix:"<<endl;

int first[row][col], second[row][col];

int i,j;
for( i=0;i<row;i++){

    cout<<"Enter value for row number: "<<i+1<<endl;
    for( j=0;j<col;j++){
        cin>>first[i][j];
    }

}


cout<<"nnnEnter Value For Second Matrix:"<<endl;
for( i=0;i<row;i++){

    cout<<"Enter value for row number: "<<i+1<<endl;

    for( j=0;j<col;j++){
        cin>>second[i][j];

    }

}

// Resultant Matrix
for( i=0;i<row;i++){

    for( j=0;j<col;j++){
        first[i][j]=first[i][j]+second[i][j];

    }

}

cout<<"nnttResultant Matrix:"<<endl;
for( i=0;i<row;i++){
    cout<< endl;
    for( j=0;j<col;j++){
        cout<<"tt"<<first[i][j]<<"    ";

    }

}
return 0;
}

Leave a Comment